Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.44
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.44! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.43 2014/04/16 16:21:24 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.1172.2.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.42 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')) {
1.1172.2.44! raeburn 1743: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1744: } else {
1745: if (defined(&domain($udom,'primary'))) {
1746: my $uhome=&domain($udom,'primary');
1747: my $rep=&reply("inst_usertypes:$udom",$uhome);
1748: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44! raeburn 1749: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1750: return (\%returnhash,\@order);
1751: }
1752: my ($hashitems,$orderitems) = split(/:/,$rep);
1753: my @pairs=split(/\&/,$hashitems);
1754: foreach my $item (@pairs) {
1755: my ($key,$value)=split(/=/,$item,2);
1756: $key = &unescape($key);
1757: next if ($key =~ /^error: 2 /);
1758: $returnhash{$key}=&thaw_unescape($value);
1759: }
1760: my @esc_order = split(/\&/,$orderitems);
1761: foreach my $item (@esc_order) {
1762: push(@order,&unescape($item));
1763: }
1764: } else {
1.1172.2.44! raeburn 1765: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1766: }
1.1172.2.44! raeburn 1767: return (\%returnhash,\@order);
1.837 raeburn 1768: }
1769: }
1770:
1.868 raeburn 1771: sub is_domainimage {
1772: my ($url) = @_;
1773: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1774: if (&domain($1) ne '') {
1775: return '1';
1776: }
1777: }
1778: return;
1779: }
1780:
1.899 raeburn 1781: sub inst_directory_query {
1782: my ($srch) = @_;
1783: my $udom = $srch->{'srchdomain'};
1784: my %results;
1785: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1786: my $outcome;
1.899 raeburn 1787: if ($homeserver ne '') {
1.904 albertel 1788: my $queryid=&reply("querysend:instdirsearch:".
1789: &escape($srch->{'srchby'}).':'.
1790: &escape($srch->{'srchterm'}).':'.
1791: &escape($srch->{'srchtype'}),$homeserver);
1792: my $host=&hostname($homeserver);
1793: if ($queryid !~/^\Q$host\E\_/) {
1794: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1795: return;
1796: }
1797: my $response = &get_query_reply($queryid);
1798: my $maxtries = 5;
1799: my $tries = 1;
1800: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1801: $response = &get_query_reply($queryid);
1802: $tries ++;
1803: }
1804:
1805: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1806: if ($response eq 'unavailable') {
1807: $outcome = $response;
1808: } else {
1809: $outcome = 'ok';
1810: my @matches = split(/\n/,$response);
1811: foreach my $match (@matches) {
1812: my ($key,$value) = split(/=/,$match);
1813: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1814: }
1.899 raeburn 1815: }
1816: }
1817: }
1.909 raeburn 1818: return ($outcome,%results);
1.899 raeburn 1819: }
1820:
1821: sub usersearch {
1822: my ($srch) = @_;
1823: my $dom = $srch->{'srchdomain'};
1824: my %results;
1825: my %libserv = &all_library();
1826: my $query = 'usersearch';
1827: foreach my $tryserver (keys(%libserv)) {
1828: if (&host_domain($tryserver) eq $dom) {
1829: my $host=&hostname($tryserver);
1830: my $queryid=
1.911 raeburn 1831: &reply("querysend:".&escape($query).':'.
1832: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1833: &escape($srch->{'srchtype'}).':'.
1834: &escape($srch->{'srchterm'}),$tryserver);
1835: if ($queryid !~/^\Q$host\E\_/) {
1836: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1837: next;
1.899 raeburn 1838: }
1839: my $reply = &get_query_reply($queryid);
1840: my $maxtries = 1;
1841: my $tries = 1;
1842: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1843: $reply = &get_query_reply($queryid);
1844: $tries ++;
1845: }
1846: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1847: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1848: } else {
1.911 raeburn 1849: my @matches;
1850: if ($reply =~ /\n/) {
1851: @matches = split(/\n/,$reply);
1852: } else {
1853: @matches = split(/\&/,$reply);
1854: }
1.899 raeburn 1855: foreach my $match (@matches) {
1856: my ($uname,$udom,%userhash);
1.911 raeburn 1857: foreach my $entry (split(/:/,$match)) {
1858: my ($key,$value) =
1859: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1860: $userhash{$key} = $value;
1861: if ($key eq 'username') {
1862: $uname = $value;
1863: } elsif ($key eq 'domain') {
1864: $udom = $value;
1.911 raeburn 1865: }
1.899 raeburn 1866: }
1867: $results{$uname.':'.$udom} = \%userhash;
1868: }
1869: }
1870: }
1871: }
1872: return %results;
1873: }
1874:
1.912 raeburn 1875: sub get_instuser {
1876: my ($udom,$uname,$id) = @_;
1877: my $homeserver = &domain($udom,'primary');
1878: my ($outcome,%results);
1879: if ($homeserver ne '') {
1880: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1881: &escape($id).':'.&escape($udom),$homeserver);
1882: my $host=&hostname($homeserver);
1883: if ($queryid !~/^\Q$host\E\_/) {
1884: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1885: return;
1886: }
1887: my $response = &get_query_reply($queryid);
1888: my $maxtries = 5;
1889: my $tries = 1;
1890: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1891: $response = &get_query_reply($queryid);
1892: $tries ++;
1893: }
1894: if (!&error($response) && $response ne 'refused') {
1895: if ($response eq 'unavailable') {
1896: $outcome = $response;
1897: } else {
1898: $outcome = 'ok';
1899: my @matches = split(/\n/,$response);
1900: foreach my $match (@matches) {
1901: my ($key,$value) = split(/=/,$match);
1902: $results{&unescape($key)} = &thaw_unescape($value);
1903: }
1904: }
1905: }
1906: }
1907: my %userinfo;
1908: if (ref($results{$uname}) eq 'HASH') {
1909: %userinfo = %{$results{$uname}};
1910: }
1911: return ($outcome,%userinfo);
1912: }
1913:
1914: sub inst_rulecheck {
1.923 raeburn 1915: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1916: my %returnhash;
1917: if ($udom ne '') {
1918: if (ref($rules) eq 'ARRAY') {
1919: @{$rules} = map {&escape($_);} (@{$rules});
1920: my $rulestr = join(':',@{$rules});
1921: my $homeserver=&domain($udom,'primary');
1922: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1923: my $response;
1924: if ($item eq 'username') {
1925: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1926: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1927: $homeserver));
1.923 raeburn 1928: } elsif ($item eq 'id') {
1929: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1930: ':'.&escape($id).':'.$rulestr,
1931: $homeserver));
1.945 raeburn 1932: } elsif ($item eq 'selfcreate') {
1933: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1934: &escape($udom).':'.&escape($uname).
1935: ':'.$rulestr,$homeserver));
1.923 raeburn 1936: }
1.912 raeburn 1937: if ($response ne 'refused') {
1938: my @pairs=split(/\&/,$response);
1939: foreach my $item (@pairs) {
1940: my ($key,$value)=split(/=/,$item,2);
1941: $key = &unescape($key);
1942: next if ($key =~ /^error: 2 /);
1943: $returnhash{$key}=&thaw_unescape($value);
1944: }
1945: }
1946: }
1947: }
1948: }
1949: return %returnhash;
1950: }
1951:
1952: sub inst_userrules {
1.923 raeburn 1953: my ($udom,$check) = @_;
1.912 raeburn 1954: my (%ruleshash,@ruleorder);
1955: if ($udom ne '') {
1956: my $homeserver=&domain($udom,'primary');
1957: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1958: my $response;
1959: if ($check eq 'id') {
1960: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1961: $homeserver);
1.943 raeburn 1962: } elsif ($check eq 'email') {
1963: $response=&reply('instemailrules:'.&escape($udom),
1964: $homeserver);
1.923 raeburn 1965: } else {
1966: $response=&reply('instuserrules:'.&escape($udom),
1967: $homeserver);
1968: }
1.912 raeburn 1969: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1970: ($response ne 'unknown_cmd') &&
1.912 raeburn 1971: ($response ne 'no_such_host')) {
1972: my ($hashitems,$orderitems) = split(/:/,$response);
1973: my @pairs=split(/\&/,$hashitems);
1974: foreach my $item (@pairs) {
1975: my ($key,$value)=split(/=/,$item,2);
1976: $key = &unescape($key);
1977: next if ($key =~ /^error: 2 /);
1978: $ruleshash{$key}=&thaw_unescape($value);
1979: }
1980: my @esc_order = split(/\&/,$orderitems);
1981: foreach my $item (@esc_order) {
1982: push(@ruleorder,&unescape($item));
1983: }
1984: }
1985: }
1986: }
1987: return (\%ruleshash,\@ruleorder);
1988: }
1989:
1.976 raeburn 1990: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1991:
1992: sub get_domain_defaults {
1.1172.2.35 raeburn 1993: my ($domain,$ignore_cache) = @_;
1994: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 1995: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 1996: unless ($ignore_cache) {
1997: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1998: if (defined($cached)) {
1999: if (ref($result) eq 'HASH') {
2000: return %{$result};
2001: }
1.943 raeburn 2002: }
2003: }
2004: my %domdefaults;
2005: my %domconfig =
1.989 raeburn 2006: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2007: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2008: 'coursedefaults','usersessions',
1.1172.2.43 raeburn 2009: 'requestauthor','selfenrollment'],$domain);
1.1172.2.41 raeburn 2010: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2011: if (ref($domconfig{'defaults'}) eq 'HASH') {
2012: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2013: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2014: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2015: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2016: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2017: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2018: } else {
2019: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2020: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2021: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2022: }
1.976 raeburn 2023: if (ref($domconfig{'quotas'}) eq 'HASH') {
2024: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2025: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2026: } else {
2027: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2028: }
1.1172.2.6 raeburn 2029: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2030: foreach my $item (@usertools) {
2031: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2032: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2033: }
2034: }
1.1172.2.29 raeburn 2035: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2036: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2037: }
1.976 raeburn 2038: }
1.985 raeburn 2039: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2040: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2041: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2042: }
2043: }
1.1172.2.9 raeburn 2044: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2045: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2046: }
1.989 raeburn 2047: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44! raeburn 2048: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2049: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2050: }
2051: }
1.1047 raeburn 2052: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.41 raeburn 2053: foreach my $type (@coursetypes) {
2054: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2055: unless ($type eq 'community') {
2056: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2057: }
2058: }
2059: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2060: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2061: }
1.1172.2.30 raeburn 2062: }
1.1047 raeburn 2063: }
1.1073 raeburn 2064: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2065: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2066: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2067: }
2068: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2069: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2070: }
2071: }
1.1172.2.41 raeburn 2072: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2073: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2074: my @settings = ('types','registered','enroll_dates','access_dates','section',
2075: 'approval','limit');
2076: foreach my $type (@coursetypes) {
2077: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2078: my @mgrdc = ();
2079: foreach my $item (@settings) {
2080: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2081: push(@mgrdc,$item);
2082: }
2083: }
2084: if (@mgrdc) {
2085: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2086: }
2087: }
2088: }
2089: }
2090: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2091: foreach my $type (@coursetypes) {
2092: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2093: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2094: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2095: }
2096: }
2097: }
2098: }
2099: }
1.1172.2.23 raeburn 2100: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2101: return %domdefaults;
2102: }
2103:
1.344 www 2104: # --------------------------------------------------- Assign a key to a student
2105:
2106: sub assign_access_key {
1.364 www 2107: #
2108: # a valid key looks like uname:udom#comments
2109: # comments are being appended
2110: #
1.498 www 2111: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2112: $kdom=
1.620 albertel 2113: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2114: $knum=
1.620 albertel 2115: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2116: $cdom=
1.620 albertel 2117: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2118: $cnum=
1.620 albertel 2119: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2120: $udom=$env{'user.name'} unless (defined($udom));
2121: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2122: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2123: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2124: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2125: # assigned to this person
2126: # - this should not happen,
1.345 www 2127: # unless something went wrong
2128: # the first time around
2129: # ready to assign
1.364 www 2130: $logentry=$1.'; '.$logentry;
1.496 www 2131: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2132: $kdom,$knum) eq 'ok') {
1.345 www 2133: # key now belongs to user
1.346 www 2134: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2135: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2136: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2137: return 'ok';
2138: } else {
2139: return
2140: 'error: Count not permanently assign key, will need to be re-entered later.';
2141: }
2142: } else {
2143: return 'error: Could not assign key, try again later.';
2144: }
1.364 www 2145: } elsif (!$existing{$ckey}) {
1.345 www 2146: # the key does not exist
2147: return 'error: The key does not exist';
2148: } else {
2149: # the key is somebody else's
2150: return 'error: The key is already in use';
2151: }
1.344 www 2152: }
2153:
1.364 www 2154: # ------------------------------------------ put an additional comment on a key
2155:
2156: sub comment_access_key {
2157: #
2158: # a valid key looks like uname:udom#comments
2159: # comments are being appended
2160: #
2161: my ($ckey,$cdom,$cnum,$logentry)=@_;
2162: $cdom=
1.620 albertel 2163: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2164: $cnum=
1.620 albertel 2165: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2166: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2167: if ($existing{$ckey}) {
2168: $existing{$ckey}.='; '.$logentry;
2169: # ready to assign
1.367 www 2170: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2171: $cdom,$cnum) eq 'ok') {
2172: return 'ok';
2173: } else {
2174: return 'error: Count not store comment.';
2175: }
2176: } else {
2177: # the key does not exist
2178: return 'error: The key does not exist';
2179: }
2180: }
2181:
1.344 www 2182: # ------------------------------------------------------ Generate a set of keys
2183:
2184: sub generate_access_keys {
1.364 www 2185: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2186: $cdom=
1.620 albertel 2187: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2188: $cnum=
1.620 albertel 2189: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2190: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2191: unless (($cdom) && ($cnum)) { return 0; }
2192: if ($number>10000) { return 0; }
2193: sleep(2); # make sure don't get same seed twice
2194: srand(time()^($$+($$<<15))); # from "Programming Perl"
2195: my $total=0;
2196: for (my $i=1;$i<=$number;$i++) {
2197: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2198: sprintf("%lx",int(100000*rand)).'-'.
2199: sprintf("%lx",int(100000*rand));
2200: $newkey=~s/1/g/g; # folks mix up 1 and l
2201: $newkey=~s/0/h/g; # and also 0 and O
2202: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2203: if ($existing{$newkey}) {
2204: $i--;
2205: } else {
1.364 www 2206: if (&put('accesskeys',
2207: { $newkey => '# generated '.localtime().
1.620 albertel 2208: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2209: '; '.$logentry },
2210: $cdom,$cnum) eq 'ok') {
1.344 www 2211: $total++;
2212: }
2213: }
2214: }
1.620 albertel 2215: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2216: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2217: return $total;
2218: }
2219:
2220: # ------------------------------------------------------- Validate an accesskey
2221:
2222: sub validate_access_key {
2223: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2224: $cdom=
1.620 albertel 2225: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2226: $cnum=
1.620 albertel 2227: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2228: $udom=$env{'user.domain'} unless (defined($udom));
2229: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2230: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2231: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2232: }
2233:
2234: # ------------------------------------- Find the section of student in a course
1.652 albertel 2235: sub devalidate_getsection_cache {
2236: my ($udom,$unam,$courseid)=@_;
2237: my $hashid="$udom:$unam:$courseid";
2238: &devalidate_cache_new('getsection',$hashid);
2239: }
1.298 matthew 2240:
1.815 albertel 2241: sub courseid_to_courseurl {
2242: my ($courseid) = @_;
2243: #already url style courseid
2244: return $courseid if ($courseid =~ m{^/});
2245:
2246: if (exists($env{'course.'.$courseid.'.num'})) {
2247: my $cnum = $env{'course.'.$courseid.'.num'};
2248: my $cdom = $env{'course.'.$courseid.'.domain'};
2249: return "/$cdom/$cnum";
2250: }
2251:
2252: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2253: if (exists($courseinfo{'num'})) {
2254: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2255: }
2256:
2257: return undef;
2258: }
2259:
1.298 matthew 2260: sub getsection {
2261: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2262: my $cachetime=1800;
1.551 albertel 2263:
2264: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2265: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2266: if (defined($cached)) { return $result; }
2267:
1.298 matthew 2268: my %Pending;
2269: my %Expired;
2270: #
2271: # Each role can either have not started yet (pending), be active,
2272: # or have expired.
2273: #
2274: # If there is an active role, we are done.
2275: #
2276: # If there is more than one role which has not started yet,
2277: # choose the one which will start sooner
2278: # If there is one role which has not started yet, return it.
2279: #
2280: # If there is more than one expired role, choose the one which ended last.
2281: # If there is a role which has expired, return it.
2282: #
1.815 albertel 2283: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2284: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2285: foreach my $key (keys(%roleshash)) {
1.479 albertel 2286: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2287: my $section=$1;
2288: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2289: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2290: my $now=time;
1.548 albertel 2291: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2292: $Expired{$end}=$section;
2293: next;
2294: }
1.548 albertel 2295: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2296: $Pending{$start}=$section;
2297: next;
2298: }
1.599 albertel 2299: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2300: }
2301: #
2302: # Presumedly there will be few matching roles from the above
2303: # loop and the sorting time will be negligible.
2304: if (scalar(keys(%Pending))) {
2305: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2306: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2307: }
2308: if (scalar(keys(%Expired))) {
2309: my @sorted = sort {$a <=> $b} keys(%Expired);
2310: my $time = pop(@sorted);
1.599 albertel 2311: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2312: }
1.599 albertel 2313: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2314: }
1.70 www 2315:
1.599 albertel 2316: sub save_cache {
2317: &purge_remembered();
1.722 albertel 2318: #&Apache::loncommon::validate_page();
1.620 albertel 2319: undef(%env);
1.780 albertel 2320: undef($env_loaded);
1.599 albertel 2321: }
1.452 albertel 2322:
1.599 albertel 2323: my $to_remember=-1;
2324: my %remembered;
2325: my %accessed;
2326: my $kicks=0;
2327: my $hits=0;
1.849 albertel 2328: sub make_key {
2329: my ($name,$id) = @_;
1.872 albertel 2330: if (length($id) > 65
2331: && length(&escape($id)) > 200) {
2332: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2333: }
1.849 albertel 2334: return &escape($name.':'.$id);
2335: }
2336:
1.599 albertel 2337: sub devalidate_cache_new {
2338: my ($name,$id,$debug) = @_;
2339: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2340: $id=&make_key($name,$id);
1.599 albertel 2341: $memcache->delete($id);
2342: delete($remembered{$id});
2343: delete($accessed{$id});
2344: }
2345:
2346: sub is_cached_new {
2347: my ($name,$id,$debug) = @_;
1.849 albertel 2348: $id=&make_key($name,$id);
1.599 albertel 2349: if (exists($remembered{$id})) {
1.1133 foxr 2350: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2351: $accessed{$id}=[&gettimeofday()];
2352: $hits++;
2353: return ($remembered{$id},1);
2354: }
2355: my $value = $memcache->get($id);
2356: if (!(defined($value))) {
2357: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2358: return (undef,undef);
1.416 albertel 2359: }
1.599 albertel 2360: if ($value eq '__undef__') {
2361: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2362: $value=undef;
2363: }
2364: &make_room($id,$value,$debug);
2365: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2366: return ($value,1);
2367: }
2368:
2369: sub do_cache_new {
2370: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2371: $id=&make_key($name,$id);
1.599 albertel 2372: my $setvalue=$value;
2373: if (!defined($setvalue)) {
2374: $setvalue='__undef__';
2375: }
1.623 albertel 2376: if (!defined($time) ) {
2377: $time=600;
2378: }
1.599 albertel 2379: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2380: my $result = $memcache->set($id,$setvalue,$time);
2381: if (! $result) {
1.872 albertel 2382: &logthis("caching of id -> $id failed");
1.910 albertel 2383: $memcache->disconnect_all();
1.872 albertel 2384: }
1.600 albertel 2385: # need to make a copy of $value
1.919 albertel 2386: &make_room($id,$value,$debug);
1.599 albertel 2387: return $value;
2388: }
2389:
2390: sub make_room {
2391: my ($id,$value,$debug)=@_;
1.919 albertel 2392:
2393: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2394: : $value;
1.599 albertel 2395: if ($to_remember<0) { return; }
2396: $accessed{$id}=[&gettimeofday()];
2397: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2398: my $to_kick;
2399: my $max_time=0;
2400: foreach my $other (keys(%accessed)) {
2401: if (&tv_interval($accessed{$other}) > $max_time) {
2402: $to_kick=$other;
2403: $max_time=&tv_interval($accessed{$other});
2404: }
2405: }
2406: delete($remembered{$to_kick});
2407: delete($accessed{$to_kick});
2408: $kicks++;
2409: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2410: return;
2411: }
2412:
1.599 albertel 2413: sub purge_remembered {
1.604 albertel 2414: #&logthis("Tossing ".scalar(keys(%remembered)));
2415: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2416: undef(%remembered);
2417: undef(%accessed);
1.428 albertel 2418: }
1.70 www 2419: # ------------------------------------- Read an entry from a user's environment
2420:
2421: sub userenvironment {
2422: my ($udom,$unam,@what)=@_;
1.976 raeburn 2423: my $items;
2424: foreach my $item (@what) {
2425: $items.=&escape($item).'&';
2426: }
2427: $items=~s/\&$//;
1.70 www 2428: my %returnhash=();
1.1009 raeburn 2429: my $uhome = &homeserver($unam,$udom);
2430: unless ($uhome eq 'no_host') {
2431: my @answer=split(/\&/,
2432: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2433: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2434: return %returnhash;
2435: }
1.1009 raeburn 2436: my $i;
2437: for ($i=0;$i<=$#what;$i++) {
2438: $returnhash{$what[$i]}=&unescape($answer[$i]);
2439: }
1.70 www 2440: }
2441: return %returnhash;
1.1 albertel 2442: }
2443:
1.617 albertel 2444: # ---------------------------------------------------------- Get a studentphoto
2445: sub studentphoto {
2446: my ($udom,$unam,$ext) = @_;
2447: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2448: if (defined($env{'request.course.id'})) {
1.708 raeburn 2449: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2450: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2451: return(&retrievestudentphoto($udom,$unam,$ext));
2452: } else {
2453: my ($result,$perm_reqd)=
1.707 albertel 2454: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2455: if ($result eq 'ok') {
2456: if (!($perm_reqd eq 'yes')) {
2457: return(&retrievestudentphoto($udom,$unam,$ext));
2458: }
2459: }
2460: }
2461: }
2462: } else {
2463: my ($result,$perm_reqd) =
1.707 albertel 2464: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2465: if ($result eq 'ok') {
2466: if (!($perm_reqd eq 'yes')) {
2467: return(&retrievestudentphoto($udom,$unam,$ext));
2468: }
2469: }
2470: }
2471: return '/adm/lonKaputt/lonlogo_broken.gif';
2472: }
2473:
2474: sub retrievestudentphoto {
2475: my ($udom,$unam,$ext,$type) = @_;
2476: my $home=&Apache::lonnet::homeserver($unam,$udom);
2477: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2478: if ($ret eq 'ok') {
2479: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2480: if ($type eq 'thumbnail') {
2481: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2482: }
2483: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2484: return $tokenurl;
2485: } else {
2486: if ($type eq 'thumbnail') {
2487: return '/adm/lonKaputt/genericstudent_tn.gif';
2488: } else {
2489: return '/adm/lonKaputt/lonlogo_broken.gif';
2490: }
1.617 albertel 2491: }
2492: }
2493:
1.263 www 2494: # -------------------------------------------------------------------- New chat
2495:
2496: sub chatsend {
1.724 raeburn 2497: my ($newentry,$anon,$group)=@_;
1.620 albertel 2498: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2499: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2500: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2501: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2502: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2503: &escape($newentry)).':'.$group,$chome);
1.292 www 2504: }
2505:
2506: # ------------------------------------------ Find current version of a resource
2507:
2508: sub getversion {
2509: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2510: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2511: return ¤tversion(&filelocation('',$fname));
2512: }
2513:
2514: sub currentversion {
2515: my $fname=shift;
2516: my $author=$fname;
2517: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2518: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2519: my $home=&homeserver($uname,$udom);
1.292 www 2520: if ($home eq 'no_host') {
2521: return -1;
2522: }
1.1112 www 2523: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2524: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2525: return -1;
2526: }
1.1112 www 2527: return $answer;
1.263 www 2528: }
2529:
1.1111 www 2530: #
2531: # Return special version number of resource if set by override, empty otherwise
2532: #
2533: sub usedversion {
2534: my $fname=shift;
2535: unless ($fname) { $fname=$env{'request.uri'}; }
2536: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2537: if ($urlversion) { return $urlversion; }
2538: return '';
2539: }
2540:
1.1 albertel 2541: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2542:
1.1 albertel 2543: sub subscribe {
2544: my $fname=shift;
1.761 raeburn 2545: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2546: $fname=~s/[\n\r]//g;
1.1 albertel 2547: my $author=$fname;
2548: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2549: my ($udom,$uname)=split(/\//,$author);
2550: my $home=homeserver($uname,$udom);
1.335 albertel 2551: if ($home eq 'no_host') {
2552: return 'not_found';
1.1 albertel 2553: }
2554: my $answer=reply("sub:$fname",$home);
1.64 www 2555: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2556: $answer.=' by '.$home;
2557: }
1.1 albertel 2558: return $answer;
2559: }
2560:
1.8 www 2561: # -------------------------------------------------------------- Replicate file
2562:
2563: sub repcopy {
2564: my $filename=shift;
1.23 www 2565: $filename=~s/\/+/\//g;
1.1142 raeburn 2566: my $londocroot = $perlvar{'lonDocRoot'};
2567: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2568: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2569: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2570: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2571: return &repcopy_userfile($filename);
2572: }
1.532 albertel 2573: $filename=~s/[\n\r]//g;
1.8 www 2574: my $transname="$filename.in.transfer";
1.828 www 2575: # FIXME: this should flock
1.607 raeburn 2576: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2577: my $remoteurl=subscribe($filename);
1.64 www 2578: if ($remoteurl =~ /^con_lost by/) {
2579: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2580: return 'unavailable';
1.8 www 2581: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2582: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2583: return 'not_found';
1.64 www 2584: } elsif ($remoteurl =~ /^rejected by/) {
2585: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2586: return 'forbidden';
1.20 www 2587: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2588: return 'ok';
1.8 www 2589: } else {
1.290 www 2590: my $author=$filename;
2591: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2592: my ($udom,$uname)=split(/\//,$author);
2593: my $home=homeserver($uname,$udom);
2594: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2595: my @parts=split(/\//,$filename);
2596: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2597: if ($path ne "$londocroot/res") {
1.8 www 2598: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2599: return 'bad_request';
1.8 www 2600: }
2601: my $count;
2602: for ($count=5;$count<$#parts;$count++) {
2603: $path.="/$parts[$count]";
2604: if ((-e $path)!=1) {
2605: mkdir($path,0777);
2606: }
2607: }
2608: my $ua=new LWP::UserAgent;
2609: my $request=new HTTP::Request('GET',"$remoteurl");
2610: my $response=$ua->request($request,$transname);
2611: if ($response->is_error()) {
2612: unlink($transname);
2613: my $message=$response->status_line;
1.672 albertel 2614: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2615: ." LWP get: $message: $filename</font>");
1.607 raeburn 2616: return 'unavailable';
1.8 www 2617: } else {
1.16 www 2618: if ($remoteurl!~/\.meta$/) {
2619: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2620: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2621: if ($mresponse->is_error()) {
2622: unlink($filename.'.meta');
2623: &logthis(
1.672 albertel 2624: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2625: }
2626: }
1.8 www 2627: rename($transname,$filename);
1.607 raeburn 2628: return 'ok';
1.8 www 2629: }
1.290 www 2630: }
1.8 www 2631: }
1.330 www 2632: }
2633:
2634: # ------------------------------------------------ Get server side include body
2635: sub ssi_body {
1.381 albertel 2636: my ($filelink,%form)=@_;
1.606 matthew 2637: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2638: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2639: }
1.953 www 2640: my $output='';
2641: my $response;
1.980 raeburn 2642: if ($filelink=~/^https?\:/) {
1.954 raeburn 2643: ($output,$response)=&externalssi($filelink);
1.953 www 2644: } else {
1.1004 droeschl 2645: $filelink .= $filelink=~/\?/ ? '&' : '?';
2646: $filelink .= 'inhibitmenu=yes';
1.953 www 2647: ($output,$response)=&ssi($filelink,%form);
2648: }
1.778 albertel 2649: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2650: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2651: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2652: if (wantarray) {
2653: return ($output, $response);
2654: } else {
2655: return $output;
2656: }
1.8 www 2657: }
2658:
1.15 www 2659: # --------------------------------------------------------- Server Side Include
2660:
1.782 albertel 2661: sub absolute_url {
2662: my ($host_name) = @_;
2663: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2664: if ($host_name eq '') {
2665: $host_name = $ENV{'SERVER_NAME'};
2666: }
2667: return $protocol.$host_name;
2668: }
2669:
1.942 foxr 2670: #
2671: # Server side include.
2672: # Parameters:
2673: # fn Possibly encrypted resource name/id.
2674: # form Hash that describes how the rendering should be done
2675: # and other things.
1.944 foxr 2676: # Returns:
1.950 raeburn 2677: # Scalar context: The content of the response.
2678: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2679: #
1.15 www 2680: sub ssi {
2681:
1.944 foxr 2682: my ($fn,%form)=@_;
1.15 www 2683: my $ua=new LWP::UserAgent;
1.23 www 2684: my $request;
1.711 albertel 2685:
2686: $form{'no_update_last_known'}=1;
1.895 albertel 2687: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2688: if (%form) {
1.782 albertel 2689: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2690: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2691: } else {
1.782 albertel 2692: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2693: }
2694:
1.15 www 2695: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2696: my $response= $ua->request($request);
1.944 foxr 2697: if (wantarray) {
1.1172.2.3 raeburn 2698: return ($response->content, $response);
1.944 foxr 2699: } else {
1.1172.2.3 raeburn 2700: return $response->content;
1.942 foxr 2701: }
1.324 www 2702: }
2703:
2704: sub externalssi {
2705: my ($url)=@_;
2706: my $ua=new LWP::UserAgent;
2707: my $request=new HTTP::Request('GET',$url);
2708: my $response=$ua->request($request);
1.954 raeburn 2709: if (wantarray) {
2710: return ($response->content, $response);
2711: } else {
2712: return $response->content;
2713: }
1.15 www 2714: }
1.254 www 2715:
1.492 albertel 2716: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2717:
2718: sub allowuploaded {
2719: my ($srcurl,$url)=@_;
2720: $url=&clutter(&declutter($url));
2721: my $dir=$url;
2722: $dir=~s/\/[^\/]+$//;
2723: my %httpref=();
2724: my $httpurl=&hreflocation('',$url);
2725: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2726: &Apache::lonnet::appenv(\%httpref);
1.254 www 2727: }
1.477 raeburn 2728:
1.1172.2.13 raeburn 2729: #
2730: # Determine if the current user should be able to edit a particular resource,
2731: # when viewing in course context.
2732: # (a) When viewing resource used to determine if "Edit" item is included in
2733: # Functions.
2734: # (b) When displaying folder contents in course editor, used to determine if
2735: # "Edit" link will be displayed alongside resource.
2736: #
2737: # input: six args -- filename (decluttered), course number, course domain,
2738: # url, symb (if registered) and group (if this is a group
2739: # item -- e.g., bulletin board, group page etc.).
2740: # output: array of five scalars --
2741: # $cfile -- url for file editing if editable on current server
2742: # $home -- homeserver of resource (i.e., for author if published,
2743: # or course if uploaded.).
2744: # $switchserver -- 1 if server switch will be needed.
2745: # $forceedit -- 1 if icon/link should be to go to edit mode
2746: # $forceview -- 1 if icon/link should be to go to view mode
2747: #
2748:
2749: sub can_edit_resource {
2750: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2751: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2752: #
2753: # For aboutme pages user can only edit his/her own.
2754: #
2755: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2756: my ($sdom,$sname) = ($1,$2);
2757: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2758: $home = $env{'user.home'};
2759: $cfile = $resurl;
2760: if ($env{'form.forceedit'}) {
2761: $forceview = 1;
2762: } else {
2763: $forceedit = 1;
2764: }
2765: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2766: } else {
2767: return;
2768: }
2769: }
2770:
2771: if ($env{'request.course.id'}) {
2772: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2773: if ($group ne '') {
2774: # if this is a group homepage or group bulletin board, check group privs
2775: my $allowed = 0;
2776: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2777: if ((&allowed('mdg',$env{'request.course.id'}.
2778: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2779: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2780: $allowed = 1;
2781: }
2782: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2783: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2784: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2785: $allowed = 1;
2786: }
2787: }
2788: if ($allowed) {
2789: $home=&homeserver($cnum,$cdom);
2790: if ($env{'form.forceedit'}) {
2791: $forceview = 1;
2792: } else {
2793: $forceedit = 1;
2794: }
2795: $cfile = $resurl;
2796: } else {
2797: return;
2798: }
2799: } else {
1.1172.2.15 raeburn 2800: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2801: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2802: return;
2803: }
2804: } elsif (!$crsedit) {
1.1172.2.13 raeburn 2805: #
2806: # No edit allowed where CC has switched to student role.
2807: #
2808: return;
2809: }
2810: }
2811: }
2812:
2813: if ($file ne '') {
2814: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2815: if (&is_course_upload($file,$cnum,$cdom)) {
2816: $uploaded = 1;
2817: $incourse = 1;
2818: if ($file =~/\.(htm|html|css|js|txt)$/) {
2819: $cfile = &hreflocation('',$file);
2820: if ($env{'form.forceedit'}) {
2821: $forceview = 1;
2822: } else {
2823: $forceedit = 1;
2824: }
2825: }
2826: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2827: $incourse = 1;
2828: if ($env{'form.forceedit'}) {
2829: $forceview = 1;
2830: } else {
2831: $forceedit = 1;
2832: }
2833: $cfile = $resurl;
2834: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2835: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2836: $incourse = 1;
2837: if ($env{'form.forceedit'}) {
2838: $forceview = 1;
2839: } else {
2840: $forceedit = 1;
2841: }
2842: $cfile = $resurl;
2843: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2844: $incourse = 1;
2845: $cfile = $resurl.'/smpedit';
2846: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2847: $incourse = 1;
2848: if ($env{'form.forceedit'}) {
2849: $forceview = 1;
2850: } else {
2851: $forceedit = 1;
2852: }
2853: $cfile = $resurl;
1.1172.2.15 raeburn 2854: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2855: $incourse = 1;
2856: if ($env{'form.forceedit'}) {
2857: $forceview = 1;
2858: } else {
2859: $forceedit = 1;
2860: }
2861: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2862: }
2863: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2864: my $template = '/res/lib/templates/simpleproblem.problem';
2865: if (&is_on_map($template)) {
2866: $incourse = 1;
2867: $forceview = 1;
2868: $cfile = $template;
2869: }
2870: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2871: $incourse = 1;
2872: if ($env{'form.forceedit'}) {
2873: $forceview = 1;
2874: } else {
2875: $forceedit = 1;
2876: }
2877: $cfile = $resurl;
2878: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2879: $incourse = 1;
2880: $forceview = 1;
2881: if ($symb) {
2882: my ($map,$id,$res)=&decode_symb($symb);
2883: $env{'request.symb'} = $symb;
2884: $cfile = &clutter($res);
2885: } else {
2886: $cfile = $env{'form.suppurl'};
2887: $cfile =~ s{^http://}{};
2888: $cfile = '/adm/wrapper/ext/'.$cfile;
2889: }
1.1172.2.31 raeburn 2890: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2891: if ($env{'form.forceedit'}) {
2892: $forceview = 1;
2893: } else {
2894: $forceedit = 1;
2895: }
2896: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2897: }
2898: }
2899: if ($uploaded || $incourse) {
2900: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 2901: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 2902: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2903: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2904: # Check that the user has permission to edit this resource
2905: my $setpriv = 1;
2906: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2907: if (defined($cfudom)) {
2908: $home=&homeserver($cfuname,$cfudom);
2909: $cfile=$file;
2910: }
2911: }
2912: if (($cfile ne '') && (!$incourse || $uploaded) &&
2913: (($home ne '') && ($home ne 'no_host'))) {
2914: my @ids=¤t_machine_ids();
2915: unless (grep(/^\Q$home\E$/,@ids)) {
2916: $switchserver=1;
2917: }
2918: }
2919: }
2920: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2921: }
2922:
2923: sub is_course_upload {
2924: my ($file,$cnum,$cdom) = @_;
2925: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2926: $uploadpath =~ s{^\/}{};
2927: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2928: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
2929: return 1;
2930: }
2931: return;
2932: }
2933:
2934: sub in_course {
2935: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2936: if ($hideprivileged) {
2937: my $skipuser;
1.1172.2.23 raeburn 2938: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2939: my @possdoms = ($cdom);
2940: if ($coursehash{'checkforpriv'}) {
2941: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2942: }
2943: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 2944: $skipuser = 1;
2945: if ($coursehash{'nothideprivileged'}) {
2946: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2947: my $user;
2948: if ($item =~ /:/) {
2949: $user = $item;
2950: } else {
2951: $user = join(':',split(/[\@]/,$item));
2952: }
2953: if ($user eq $uname.':'.$udom) {
2954: undef($skipuser);
2955: last;
2956: }
2957: }
2958: }
2959: if ($skipuser) {
2960: return 0;
2961: }
2962: }
2963: }
2964: $type ||= 'any';
2965: if (!defined($cdom) || !defined($cnum)) {
2966: my $cid = $env{'request.course.id'};
2967: $cdom = $env{'course.'.$cid.'.domain'};
2968: $cnum = $env{'course.'.$cid.'.num'};
2969: }
2970: my $typesref;
2971: if (($type eq 'any') || ($type eq 'all')) {
2972: $typesref = ['active','previous','future'];
2973: } elsif ($type eq 'previous' || $type eq 'future') {
2974: $typesref = [$type];
2975: }
2976: my %roles = &get_my_roles($uname,$udom,'userroles',
2977: $typesref,undef,[$cdom]);
2978: my ($tmp) = keys(%roles);
2979: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
2980: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
2981: if (@course_roles > 0) {
2982: return 1;
2983: }
2984: return 0;
2985: }
2986:
1.478 albertel 2987: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2988: # input: action, courseID, current domain, intended
1.637 raeburn 2989: # path to file, source of file, instruction to parse file for objects,
2990: # ref to hash for embedded objects,
2991: # ref to hash for codebase of java objects.
1.1095 raeburn 2992: # reference to scalar to accommodate mime type determined
2993: # from File::MMagic if $parser = parse.
1.637 raeburn 2994: #
1.485 raeburn 2995: # output: url to file (if action was uploaddoc),
2996: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2997: #
1.478 albertel 2998: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2999: # course.
1.477 raeburn 3000: #
1.478 albertel 3001: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3002: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3003: # course's home server.
1.477 raeburn 3004: #
1.478 albertel 3005: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3006: # be copied from $source (current location) to
3007: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3008: # and will then be copied to
3009: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3010: # course's home server.
1.485 raeburn 3011: #
1.481 raeburn 3012: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3013: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3014: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3015: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3016: # in course's home server.
1.637 raeburn 3017: #
1.477 raeburn 3018:
3019: sub process_coursefile {
1.1095 raeburn 3020: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3021: $mimetype)=@_;
1.477 raeburn 3022: my $fetchresult;
1.638 albertel 3023: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3024: if ($action eq 'propagate') {
1.638 albertel 3025: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3026: $home);
1.481 raeburn 3027: } else {
1.477 raeburn 3028: my $fpath = '';
3029: my $fname = $file;
1.478 albertel 3030: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3031: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3032: my $filepath = &build_filepath($fpath);
1.481 raeburn 3033: if ($action eq 'copy') {
3034: if ($source eq '') {
3035: $fetchresult = 'no source file';
3036: return $fetchresult;
3037: } else {
3038: my $destination = $filepath.'/'.$fname;
3039: rename($source,$destination);
3040: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3041: $home);
1.481 raeburn 3042: }
3043: } elsif ($action eq 'uploaddoc') {
3044: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3045: print $fh $env{'form.'.$source};
1.481 raeburn 3046: close($fh);
1.637 raeburn 3047: if ($parser eq 'parse') {
1.1024 raeburn 3048: my $mm = new File::MMagic;
1.1095 raeburn 3049: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3050: if ($type eq 'text/html') {
1.1024 raeburn 3051: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3052: unless ($parse_result eq 'ok') {
3053: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3054: }
1.637 raeburn 3055: }
1.1095 raeburn 3056: if (ref($mimetype)) {
3057: $$mimetype = $type;
3058: }
1.637 raeburn 3059: }
1.477 raeburn 3060: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3061: $home);
1.481 raeburn 3062: if ($fetchresult eq 'ok') {
3063: return '/uploaded/'.$fpath.'/'.$fname;
3064: } else {
3065: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3066: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3067: return '/adm/notfound.html';
3068: }
1.477 raeburn 3069: }
3070: }
1.485 raeburn 3071: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3072: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3073: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3074: }
3075: return $fetchresult;
3076: }
3077:
1.637 raeburn 3078: sub build_filepath {
3079: my ($fpath) = @_;
3080: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3081: unless ($fpath eq '') {
3082: my @parts=split('/',$fpath);
3083: foreach my $part (@parts) {
3084: $filepath.= '/'.$part;
3085: if ((-e $filepath)!=1) {
3086: mkdir($filepath,0777);
3087: }
3088: }
3089: }
3090: return $filepath;
3091: }
3092:
3093: sub store_edited_file {
1.638 albertel 3094: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3095: my $file = $primary_url;
3096: $file =~ s#^/uploaded/$docudom/$docuname/##;
3097: my $fpath = '';
3098: my $fname = $file;
3099: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3100: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3101: my $filepath = &build_filepath($fpath);
3102: open(my $fh,'>'.$filepath.'/'.$fname);
3103: print $fh $content;
3104: close($fh);
1.638 albertel 3105: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3106: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3107: $home);
1.637 raeburn 3108: if ($$fetchresult eq 'ok') {
3109: return '/uploaded/'.$fpath.'/'.$fname;
3110: } else {
1.638 albertel 3111: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3112: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3113: return '/adm/notfound.html';
3114: }
3115: }
3116:
1.531 albertel 3117: sub clean_filename {
1.831 albertel 3118: my ($fname,$args)=@_;
1.315 www 3119: # Replace Windows backslashes by forward slashes
1.257 www 3120: $fname=~s/\\/\//g;
1.831 albertel 3121: if (!$args->{'keep_path'}) {
3122: # Get rid of everything but the actual filename
3123: $fname=~s/^.*\/([^\/]+)$/$1/;
3124: }
1.315 www 3125: # Replace spaces by underscores
3126: $fname=~s/\s+/\_/g;
3127: # Replace all other weird characters by nothing
1.831 albertel 3128: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3129: # Replace all .\d. sequences with _\d. so they no longer look like version
3130: # numbers
3131: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3132: return $fname;
3133: }
1.1051 raeburn 3134: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3135: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3136: # image with the same aspect ratio as the original, but with dimensions which do
3137: # not exceed $resizewidth and $resizeheight.
3138:
1.984 neumanie 3139: sub resizeImage {
1.1051 raeburn 3140: my ($img_path,$resizewidth,$resizeheight) = @_;
3141: my $ima = Image::Magick->new;
3142: my $resized;
3143: if (-e $img_path) {
3144: $ima->Read($img_path);
3145: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3146: my $width = $ima->Get('width');
3147: my $height = $ima->Get('height');
3148: if ($width > $resizewidth) {
3149: my $factor = $width/$resizewidth;
3150: my $newheight = $height/$factor;
3151: $ima->Scale(width=>$resizewidth,height=>$newheight);
3152: $resized = 1;
3153: }
3154: }
3155: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3156: my $width = $ima->Get('width');
3157: my $height = $ima->Get('height');
3158: if ($height > $resizeheight) {
3159: my $factor = $height/$resizeheight;
3160: my $newwidth = $width/$factor;
3161: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3162: $resized = 1;
3163: }
3164: }
3165: if ($resized) {
3166: $ima->Write($img_path);
3167: }
3168: }
3169: return;
1.977 amueller 3170: }
3171:
1.608 albertel 3172: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3173: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3174: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3175: # $context - possible values: coursedoc, existingfile, overwrite,
3176: # canceloverwrite, or ''.
3177: # if 'coursedoc': upload to the current course
3178: # if 'existingfile': write file to tmp/overwrites directory
3179: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3180: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3181: # $subdir - directory in userfile to store the file into
1.858 raeburn 3182: # $parser - instruction to parse file for objects ($parser = parse)
3183: # $allfiles - reference to hash for embedded objects
3184: # $codebase - reference to hash for codebase of java objects
3185: # $desuname - username for permanent storage of uploaded file
3186: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3187: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3188: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3189: # $resizewidth - width (pixels) to which to resize uploaded image
3190: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3191: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3192: # from File::MMagic.
1.858 raeburn 3193: #
1.686 albertel 3194: # output: url of file in userspace, or error: <message>
3195: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3196:
1.531 albertel 3197: sub userfileupload {
1.1090 raeburn 3198: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3199: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3200: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3201: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3202: $fname=&clean_filename($fname);
1.1090 raeburn 3203: # See if there is anything left
1.257 www 3204: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3205: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3206: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3207: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3208: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3209: my $now = time;
1.1090 raeburn 3210: my $filepath;
1.1095 raeburn 3211: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3212: $filepath = 'tmp/helprequests/'.$now;
3213: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3214: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3215: '_'.$env{'user.domain'}.'/pending';
3216: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3217: my ($docuname,$docudom);
3218: if ($destudom) {
3219: $docudom = $destudom;
3220: } else {
3221: $docudom = $env{'user.domain'};
3222: }
3223: if ($destuname) {
3224: $docuname = $destuname;
3225: } else {
3226: $docuname = $env{'user.name'};
3227: }
3228: if (exists($env{'form.group'})) {
3229: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3230: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3231: }
3232: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3233: if ($context eq 'canceloverwrite') {
3234: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3235: if (-e $tempfile) {
3236: my @info = stat($tempfile);
3237: if ($info[9] eq $env{'form.timestamp'}) {
3238: unlink($tempfile);
3239: }
3240: }
3241: return;
1.523 raeburn 3242: }
3243: }
1.1090 raeburn 3244: # Create the directory if not present
1.741 raeburn 3245: my @parts=split(/\//,$filepath);
3246: my $fullpath = $perlvar{'lonDaemons'};
3247: for (my $i=0;$i<@parts;$i++) {
3248: $fullpath .= '/'.$parts[$i];
3249: if ((-e $fullpath)!=1) {
3250: mkdir($fullpath,0777);
3251: }
3252: }
3253: open(my $fh,'>'.$fullpath.'/'.$fname);
3254: print $fh $env{'form.'.$formname};
3255: close($fh);
1.1090 raeburn 3256: if ($context eq 'existingfile') {
3257: my @info = stat($fullpath.'/'.$fname);
3258: return ($fullpath.'/'.$fname,$info[9]);
3259: } else {
3260: return $fullpath.'/'.$fname;
3261: }
1.523 raeburn 3262: }
1.995 raeburn 3263: if ($subdir eq 'scantron') {
3264: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3265: } else {
1.995 raeburn 3266: $fname="$subdir/$fname";
3267: }
1.1090 raeburn 3268: if ($context eq 'coursedoc') {
1.638 albertel 3269: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3270: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3271: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3272: return &finishuserfileupload($docuname,$docudom,
3273: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3274: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3275: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3276: } else {
1.1172.2.21 raeburn 3277: if ($env{'form.folder'}) {
3278: $fname=$env{'form.folder'}.'/'.$fname;
3279: }
1.638 albertel 3280: return &process_coursefile('uploaddoc',$docuname,$docudom,
3281: $fname,$formname,$parser,
1.1095 raeburn 3282: $allfiles,$codebase,$mimetype);
1.481 raeburn 3283: }
1.719 banghart 3284: } elsif (defined($destuname)) {
3285: my $docuname=$destuname;
3286: my $docudom=$destudom;
1.860 raeburn 3287: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3288: $parser,$allfiles,$codebase,
1.1051 raeburn 3289: $thumbwidth,$thumbheight,
1.1095 raeburn 3290: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3291: } else {
1.638 albertel 3292: my $docuname=$env{'user.name'};
3293: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3294: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3295: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3296: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3297: }
1.860 raeburn 3298: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3299: $parser,$allfiles,$codebase,
1.1051 raeburn 3300: $thumbwidth,$thumbheight,
1.1095 raeburn 3301: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3302: }
1.271 www 3303: }
3304:
3305: sub finishuserfileupload {
1.860 raeburn 3306: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3307: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3308: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3309: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3310:
1.860 raeburn 3311: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3312: $file=$fname;
3313: if ($fname=~m|/|) {
3314: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3315: $path.=$fnamepath.'/';
3316: }
1.259 www 3317: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3318: my $count;
3319: for ($count=4;$count<=$#parts;$count++) {
3320: $filepath.="/$parts[$count]";
3321: if ((-e $filepath)!=1) {
3322: mkdir($filepath,0777);
3323: }
3324: }
1.984 neumanie 3325:
1.258 www 3326: # Save the file
3327: {
1.701 albertel 3328: if (!open(FH,'>'.$filepath.'/'.$file)) {
3329: &logthis('Failed to create '.$filepath.'/'.$file);
3330: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3331: return '/adm/notfound.html';
3332: }
1.1090 raeburn 3333: if ($context eq 'overwrite') {
1.1117 foxr 3334: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3335: my $target = $filepath.'/'.$file;
3336: if (-e $source) {
3337: my @info = stat($source);
3338: if ($info[9] eq $env{'form.timestamp'}) {
3339: unless (&File::Copy::move($source,$target)) {
3340: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3341: return "Moving from $source failed";
3342: }
3343: } else {
3344: return "Temporary file: $source had unexpected date/time for last modification";
3345: }
3346: } else {
3347: return "Temporary file: $source missing";
3348: }
3349: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3350: &logthis('Failed to write to '.$filepath.'/'.$file);
3351: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3352: return '/adm/notfound.html';
3353: }
1.570 albertel 3354: close(FH);
1.1051 raeburn 3355: if ($resizewidth && $resizeheight) {
3356: my $mm = new File::MMagic;
3357: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3358: if ($mime_type =~ m{^image/}) {
3359: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3360: }
1.977 amueller 3361: }
1.258 www 3362: }
1.1152 raeburn 3363: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3364: if (ref($mimetype)) {
3365: if ($$mimetype eq '') {
3366: my $mm = new File::MMagic;
3367: my $type = $mm->checktype_filename($filepath.'/'.$file);
3368: $$mimetype = $type;
3369: }
3370: }
3371: }
1.637 raeburn 3372: if ($parser eq 'parse') {
1.1152 raeburn 3373: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3374: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3375: $allfiles,$codebase);
3376: unless ($parse_result eq 'ok') {
3377: &logthis('Failed to parse '.$filepath.$file.
3378: ' for embedded media: '.$parse_result);
3379: }
1.637 raeburn 3380: }
3381: }
1.860 raeburn 3382: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3383: my $input = $filepath.'/'.$file;
3384: my $output = $filepath.'/'.'tn-'.$file;
3385: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3386: system("convert -sample $thumbsize $input $output");
3387: if (-e $filepath.'/'.'tn-'.$file) {
3388: $fetchthumb = 1;
3389: }
3390: }
1.858 raeburn 3391:
1.259 www 3392: # Notify homeserver to grep it
3393: #
1.984 neumanie 3394: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3395: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3396: if ($fetchresult eq 'ok') {
1.860 raeburn 3397: if ($fetchthumb) {
3398: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3399: if ($thumbresult ne 'ok') {
3400: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3401: $docuhome.': '.$thumbresult);
3402: }
3403: }
1.259 www 3404: #
1.258 www 3405: # Return the URL to it
1.494 albertel 3406: return '/uploaded/'.$path.$file;
1.263 www 3407: } else {
1.494 albertel 3408: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3409: ': '.$fetchresult);
1.263 www 3410: return '/adm/notfound.html';
1.858 raeburn 3411: }
1.493 albertel 3412: }
3413:
1.637 raeburn 3414: sub extract_embedded_items {
1.961 raeburn 3415: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3416: my @state = ();
1.1164 raeburn 3417: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3418: my %javafiles = (
3419: codebase => '',
3420: code => '',
3421: archive => ''
3422: );
3423: my %mediafiles = (
3424: src => '',
3425: movie => '',
3426: );
1.648 raeburn 3427: my $p;
3428: if ($content) {
3429: $p = HTML::LCParser->new($content);
3430: } else {
1.961 raeburn 3431: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3432: }
1.641 albertel 3433: while (my $t=$p->get_token()) {
1.640 albertel 3434: if ($t->[0] eq 'S') {
3435: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3436: push(@state, $tagname);
1.648 raeburn 3437: if (lc($tagname) eq 'allow') {
3438: &add_filetype($allfiles,$attr->{'src'},'src');
3439: }
1.640 albertel 3440: if (lc($tagname) eq 'img') {
3441: &add_filetype($allfiles,$attr->{'src'},'src');
3442: }
1.886 albertel 3443: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3444: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3445: &add_filetype($allfiles,$attr->{'href'},'href');
3446: }
1.886 albertel 3447: }
1.645 raeburn 3448: if (lc($tagname) eq 'script') {
1.1164 raeburn 3449: my $src;
1.645 raeburn 3450: if ($attr->{'archive'} =~ /\.jar$/i) {
3451: &add_filetype($allfiles,$attr->{'archive'},'archive');
3452: } else {
1.1164 raeburn 3453: if ($attr->{'src'} ne '') {
3454: $src = $attr->{'src'};
3455: &add_filetype($allfiles,$src,'src');
3456: }
3457: }
3458: my $text = $p->get_trimmed_text();
3459: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3460: my @swfargs = split(/,/,$1);
3461: foreach my $item (@swfargs) {
3462: $item =~ s/["']//g;
3463: $item =~ s/^\s+//;
3464: $item =~ s/\s+$//;
3465: }
3466: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3467: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3468: push(@{$related{$swfargs[0]}},$swfargs[2]);
3469: } else {
3470: $related{$swfargs[0]} = [$swfargs[2]];
3471: }
3472: }
1.645 raeburn 3473: }
3474: }
3475: if (lc($tagname) eq 'link') {
3476: if (lc($attr->{'rel'}) eq 'stylesheet') {
3477: &add_filetype($allfiles,$attr->{'href'},'href');
3478: }
3479: }
1.640 albertel 3480: if (lc($tagname) eq 'object' ||
3481: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3482: foreach my $item (keys(%javafiles)) {
3483: $javafiles{$item} = '';
3484: }
1.1164 raeburn 3485: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3486: $lastids{lc($tagname)} = $attr->{'id'};
3487: }
1.640 albertel 3488: }
3489: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3490: my $name = lc($attr->{'name'});
3491: foreach my $item (keys(%javafiles)) {
3492: if ($name eq $item) {
3493: $javafiles{$item} = $attr->{'value'};
3494: last;
3495: }
3496: }
1.1164 raeburn 3497: my $pathfrom;
1.640 albertel 3498: foreach my $item (keys(%mediafiles)) {
3499: if ($name eq $item) {
1.1164 raeburn 3500: $pathfrom = $attr->{'value'};
3501: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3502: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3503: last;
3504: }
3505: }
1.1164 raeburn 3506: if ($name eq 'flashvars') {
3507: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3508: }
3509: if ($pathfrom ne '') {
3510: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3511: $pathfrom);
3512: }
1.640 albertel 3513: }
3514: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3515: foreach my $item (keys(%javafiles)) {
3516: if ($attr->{$item}) {
3517: $javafiles{$item} = $attr->{$item};
3518: last;
3519: }
3520: }
3521: foreach my $item (keys(%mediafiles)) {
3522: if ($attr->{$item}) {
3523: &add_filetype($allfiles,$attr->{$item},$item);
3524: last;
3525: }
3526: }
1.1164 raeburn 3527: if (lc($tagname) eq 'embed') {
3528: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3529: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3530: $attr->{'src'});
3531: }
3532: }
1.640 albertel 3533: }
1.1172.2.35 raeburn 3534: if (lc($tagname) eq 'iframe') {
3535: my $src = $attr->{'src'} ;
3536: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3537: &add_filetype($allfiles,$src,'src');
3538: } elsif ($src =~ m{^/}) {
3539: if ($env{'request.course.id'}) {
3540: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3541: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3542: my $url = &hreflocation('',$fullpath);
3543: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3544: my $relpath = $1;
3545: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3546: &add_filetype($allfiles,$1,'src');
3547: }
3548: }
3549: }
3550: }
3551: }
1.1164 raeburn 3552: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3553: pop(@state);
1.1164 raeburn 3554: }
1.640 albertel 3555: } elsif ($t->[0] eq 'E') {
3556: my ($tagname) = ($t->[1]);
3557: if ($javafiles{'codebase'} ne '') {
3558: $javafiles{'codebase'} .= '/';
3559: }
3560: if (lc($tagname) eq 'applet' ||
3561: lc($tagname) eq 'object' ||
3562: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3563: ) {
3564: foreach my $item (keys(%javafiles)) {
3565: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3566: my $file=$javafiles{'codebase'}.$javafiles{$item};
3567: &add_filetype($allfiles,$file,$item);
3568: }
3569: }
3570: }
3571: pop @state;
3572: }
3573: }
1.1164 raeburn 3574: foreach my $id (sort(keys(%flashvars))) {
3575: if ($shockwave{$id} ne '') {
3576: my @pairs = split(/\&/,$flashvars{$id});
3577: foreach my $pair (@pairs) {
3578: my ($key,$value) = split(/\=/,$pair);
3579: if ($key eq 'thumb') {
3580: &add_filetype($allfiles,$value,$key);
3581: } elsif ($key eq 'content') {
3582: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3583: my ($ext) = ($value =~ /\.([^.]+)$/);
3584: if ($ext ne '') {
3585: &add_filetype($allfiles,$path.$value,$ext);
3586: }
3587: }
3588: }
3589: }
3590: }
1.637 raeburn 3591: return 'ok';
3592: }
3593:
1.639 albertel 3594: sub add_filetype {
3595: my ($allfiles,$file,$type)=@_;
3596: if (exists($allfiles->{$file})) {
3597: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3598: push(@{$allfiles->{$file}}, &escape($type));
3599: }
3600: } else {
3601: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3602: }
3603: }
3604:
1.1164 raeburn 3605: sub embedded_dependency {
3606: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3607: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3608: if (($identifier ne '') &&
3609: (ref($related->{$identifier}) eq 'ARRAY') &&
3610: ($pathfrom ne '')) {
3611: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3612: foreach my $dep (@{$related->{$identifier}}) {
3613: &add_filetype($allfiles,$path.$dep,'object');
3614: }
3615: }
3616: }
3617: return;
3618: }
3619:
1.493 albertel 3620: sub removeuploadedurl {
1.984 neumanie 3621: my ($url)=@_;
3622: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3623: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3624: }
3625:
3626: sub removeuserfile {
3627: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3628: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3629: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3630: if ($result eq 'ok') {
1.798 raeburn 3631: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3632: my $metafile = $fname.'.meta';
3633: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3634: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3635: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3636: my $sqlresult =
1.823 albertel 3637: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3638: 'portfolio_metadata',$group,
3639: 'delete');
1.798 raeburn 3640: }
3641: }
3642: return $result;
1.257 www 3643: }
1.15 www 3644:
1.530 albertel 3645: sub mkdiruserfile {
3646: my ($docuname,$docudom,$dir)=@_;
3647: my $home=&homeserver($docuname,$docudom);
3648: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3649: }
3650:
1.531 albertel 3651: sub renameuserfile {
3652: my ($docuname,$docudom,$old,$new)=@_;
3653: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3654: my $result = &reply("renameuserfile:$docudom:$docuname:".
3655: &escape("$old").':'.&escape("$new"),$home);
3656: if ($result eq 'ok') {
3657: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3658: my $oldmeta = $old.'.meta';
3659: my $newmeta = $new.'.meta';
3660: my $metaresult =
3661: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3662: my $url = "/uploaded/$docudom/$docuname/$old";
3663: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3664: my $sqlresult =
1.823 albertel 3665: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3666: 'portfolio_metadata',$group,
3667: 'delete');
1.798 raeburn 3668: }
3669: }
3670: return $result;
1.531 albertel 3671: }
3672:
1.14 www 3673: # ------------------------------------------------------------------------- Log
3674:
3675: sub log {
3676: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3677: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3678: }
3679:
3680: # ------------------------------------------------------------------ Course Log
1.352 www 3681: #
3682: # This routine flushes several buffers of non-mission-critical nature
3683: #
1.157 www 3684:
3685: sub flushcourselogs {
1.352 www 3686: &logthis('Flushing log buffers');
3687: #
3688: # course logs
3689: # This is a log of all transactions in a course, which can be used
3690: # for data mining purposes
3691: #
3692: # It also collects the courseid database, which lists last transaction
3693: # times and course titles for all courseids
3694: #
3695: my %courseidbuffer=();
1.921 raeburn 3696: foreach my $crsid (keys(%courselogs)) {
1.352 www 3697: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3698: &escape($courselogs{$crsid}),
3699: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3700: delete $courselogs{$crsid};
3701: } else {
3702: &logthis('Failed to flush log buffer for '.$crsid);
3703: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3704: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3705: " exceeded maximum size, deleting.</font>");
3706: delete $courselogs{$crsid};
3707: }
1.352 www 3708: }
1.920 raeburn 3709: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3710: 'description' => $coursedescrbuf{$crsid},
3711: 'inst_code' => $courseinstcodebuf{$crsid},
3712: 'type' => $coursetypebuf{$crsid},
3713: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3714: };
1.191 harris41 3715: }
1.352 www 3716: #
3717: # Write course id database (reverse lookup) to homeserver of courses
3718: # Is used in pickcourse
3719: #
1.840 albertel 3720: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3721: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3722: $courseidbuffer{$crs_home},
3723: $crs_home,'timeonly');
1.352 www 3724: }
3725: #
3726: # File accesses
3727: # Writes to the dynamic metadata of resources to get hit counts, etc.
3728: #
1.449 matthew 3729: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3730: if ($entry =~ /___count$/) {
3731: my ($dom,$name);
1.807 albertel 3732: ($dom,$name,undef)=
1.811 albertel 3733: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3734: if (! defined($dom) || $dom eq '' ||
3735: ! defined($name) || $name eq '') {
1.620 albertel 3736: my $cid = $env{'request.course.id'};
3737: $dom = $env{'request.'.$cid.'.domain'};
3738: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3739: }
1.450 matthew 3740: my $value = $accesshash{$entry};
3741: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3742: my %temphash=($url => $value);
1.449 matthew 3743: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3744: if ($result eq 'ok') {
3745: delete $accesshash{$entry};
3746: }
3747: } else {
1.811 albertel 3748: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3749: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3750: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3751: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3752: delete $accesshash{$entry};
3753: }
1.185 www 3754: }
1.191 harris41 3755: }
1.352 www 3756: #
3757: # Roles
3758: # Reverse lookup of user roles for course faculty/staff and co-authorship
3759: #
1.800 albertel 3760: foreach my $entry (keys(%userrolehash)) {
1.351 www 3761: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3762: split(/\:/,$entry);
3763: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3764: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3765: $rudom,$runame) eq 'ok') {
3766: delete $userrolehash{$entry};
3767: }
3768: }
1.662 raeburn 3769: #
3770: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3771: #
3772: my %domrolebuffer = ();
1.1000 raeburn 3773: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3774: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3775: if ($domrolebuffer{$rudom}) {
3776: $domrolebuffer{$rudom}.='&'.&escape($entry).
3777: '='.&escape($domainrolehash{$entry});
3778: } else {
3779: $domrolebuffer{$rudom}.=&escape($entry).
3780: '='.&escape($domainrolehash{$entry});
3781: }
3782: delete $domainrolehash{$entry};
3783: }
3784: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3785: my %servers = &get_servers($dom,'library');
3786: foreach my $tryserver (keys(%servers)) {
3787: unless (&reply('domroleput:'.$dom.':'.
3788: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3789: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3790: }
1.662 raeburn 3791: }
3792: }
1.186 www 3793: $dumpcount++;
1.157 www 3794: }
3795:
3796: sub courselog {
3797: my $what=shift;
1.158 www 3798: $what=time.':'.$what;
1.620 albertel 3799: unless ($env{'request.course.id'}) { return ''; }
3800: $coursedombuf{$env{'request.course.id'}}=
3801: $env{'course.'.$env{'request.course.id'}.'.domain'};
3802: $coursenumbuf{$env{'request.course.id'}}=
3803: $env{'course.'.$env{'request.course.id'}.'.num'};
3804: $coursehombuf{$env{'request.course.id'}}=
3805: $env{'course.'.$env{'request.course.id'}.'.home'};
3806: $coursedescrbuf{$env{'request.course.id'}}=
3807: $env{'course.'.$env{'request.course.id'}.'.description'};
3808: $courseinstcodebuf{$env{'request.course.id'}}=
3809: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3810: $courseownerbuf{$env{'request.course.id'}}=
3811: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3812: $coursetypebuf{$env{'request.course.id'}}=
3813: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3814: if (defined $courselogs{$env{'request.course.id'}}) {
3815: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3816: } else {
1.620 albertel 3817: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3818: }
1.620 albertel 3819: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3820: &flushcourselogs();
3821: }
1.158 www 3822: }
3823:
3824: sub courseacclog {
3825: my $fnsymb=shift;
1.620 albertel 3826: unless ($env{'request.course.id'}) { return ''; }
3827: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3828: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3829: $what.=':POST';
1.583 matthew 3830: # FIXME: Probably ought to escape things....
1.800 albertel 3831: foreach my $key (keys(%env)) {
3832: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3833: my $formitem = $1;
3834: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3835: $what.=':'.$formitem.'='.$env{$key};
3836: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3837: $what.=':'.$formitem.'='.$env{$key};
3838: }
1.158 www 3839: }
1.191 harris41 3840: }
1.583 matthew 3841: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3842: # FIXME: We should not be depending on a form parameter that someone
3843: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3844: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3845: $what.= ':POST';
3846: # FIXME: Probably ought to escape things....
3847: foreach my $element ('courseexp','crsfulltext','crsrelated',
3848: 'crsdiscuss') {
1.620 albertel 3849: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3850: }
3851: }
1.158 www 3852: }
3853: &courselog($what);
1.149 www 3854: }
3855:
1.185 www 3856: sub countacc {
3857: my $url=&declutter(shift);
1.458 matthew 3858: return if (! defined($url) || $url eq '');
1.620 albertel 3859: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3860: #
3861: # Mark that this url was used in this course
3862: #
1.620 albertel 3863: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3864: #
3865: # Increase the access count for this resource in this child process
3866: #
1.281 www 3867: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3868: $accesshash{$key}++;
1.185 www 3869: }
1.349 www 3870:
1.361 www 3871: sub linklog {
3872: my ($from,$to)=@_;
3873: $from=&declutter($from);
3874: $to=&declutter($to);
3875: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3876: $accesshash{$to.'___'.$from.'___goto'}=1;
3877: }
1.1160 www 3878:
3879: sub statslog {
3880: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3881: if ($users<2) { return; }
3882: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3883: 'course' => $env{'request.course.id'},
3884: 'sections' => '"all"',
3885: 'num_students' => $users,
3886: 'part' => $part,
3887: 'symb' => $symb,
3888: 'mean_tries' => $av_attempts,
3889: 'deg_of_diff' => $degdiff});
3890: foreach my $key (keys(%dynstore)) {
3891: $accesshash{$key}=$dynstore{$key};
3892: }
3893: }
1.361 www 3894:
1.349 www 3895: sub userrolelog {
3896: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3897: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3898: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3899: $userrolehash
3900: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3901: =$tend.':'.$tstart;
1.662 raeburn 3902: }
1.1169 droeschl 3903: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3904: $userrolehash
3905: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3906: =$tend.':'.$tstart;
3907: }
1.1169 droeschl 3908: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3909: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3910: $domainrolehash
3911: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3912: = $tend.':'.$tstart;
3913: }
1.351 www 3914: }
3915:
1.957 raeburn 3916: sub courserolelog {
3917: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 3918: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3919: my $cdom = $1;
3920: my $cnum = $2;
3921: my $sec = $3;
3922: my $namespace = 'rolelog';
3923: my %storehash = (
3924: role => $trole,
3925: start => $tstart,
3926: end => $tend,
3927: selfenroll => $selfenroll,
3928: context => $context,
3929: );
3930: if ($trole eq 'gr') {
3931: $namespace = 'groupslog';
3932: $storehash{'group'} = $sec;
3933: } else {
3934: $storehash{'section'} = $sec;
3935: }
3936: &write_log('course',$namespace,\%storehash,$delflag,$username,
3937: $domain,$cnum,$cdom);
3938: if (($trole ne 'st') || ($sec ne '')) {
3939: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3940: }
3941: }
3942: return;
3943: }
3944:
1.1172.2.9 raeburn 3945: sub domainrolelog {
3946: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3947: if ($area =~ m{^/($match_domain)/$}) {
3948: my $cdom = $1;
3949: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3950: my $namespace = 'rolelog';
3951: my %storehash = (
3952: role => $trole,
3953: start => $tstart,
3954: end => $tend,
3955: context => $context,
3956: );
3957: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3958: $domain,$domconfiguser,$cdom);
3959: }
3960: return;
3961:
3962: }
3963:
3964: sub coauthorrolelog {
3965: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3966: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3967: my $audom = $1;
3968: my $auname = $2;
3969: my $namespace = 'rolelog';
3970: my %storehash = (
3971: role => $trole,
3972: start => $tstart,
3973: end => $tend,
3974: context => $context,
3975: );
3976: &write_log('author',$namespace,\%storehash,$delflag,$username,
3977: $domain,$auname,$audom);
3978: }
3979: return;
3980: }
3981:
1.351 www 3982: sub get_course_adv_roles {
1.948 raeburn 3983: my ($cid,$codes) = @_;
1.620 albertel 3984: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3985: my %coursehash=&coursedescription($cid);
1.988 raeburn 3986: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3987: my %nothide=();
1.800 albertel 3988: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3989: if ($user !~ /:/) {
3990: $nothide{join(':',split(/[\@]/,$user))}=1;
3991: } else {
3992: $nothide{$user}=1;
3993: }
1.470 www 3994: }
1.1172.2.23 raeburn 3995: my @possdoms = ($coursehash{'domain'});
3996: if ($coursehash{'checkforpriv'}) {
3997: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3998: }
1.351 www 3999: my %returnhash=();
4000: my %dumphash=
4001: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4002: my $now=time;
1.997 raeburn 4003: my %privileged;
1.1000 raeburn 4004: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4005: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4006: if (($tstart) && ($tstart<0)) { next; }
4007: if (($tend) && ($tend<$now)) { next; }
4008: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4009: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4010: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4011: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4012: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4013: if ($role eq 'cr') { next; }
1.948 raeburn 4014: if ($codes) {
4015: if ($section) { $role .= ':'.$section; }
4016: if ($returnhash{$role}) {
4017: $returnhash{$role}.=','.$username.':'.$domain;
4018: } else {
4019: $returnhash{$role}=$username.':'.$domain;
4020: }
1.351 www 4021: } else {
1.988 raeburn 4022: my $key=&plaintext($role,$crstype);
1.973 bisitz 4023: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4024: if ($returnhash{$key}) {
4025: $returnhash{$key}.=','.$username.':'.$domain;
4026: } else {
4027: $returnhash{$key}=$username.':'.$domain;
4028: }
1.351 www 4029: }
1.948 raeburn 4030: }
1.400 www 4031: return %returnhash;
4032: }
4033:
4034: sub get_my_roles {
1.937 raeburn 4035: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4036: unless (defined($uname)) { $uname=$env{'user.name'}; }
4037: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4038: my (%dumphash,%nothide);
1.1086 raeburn 4039: if ($context eq 'userroles') {
1.1166 raeburn 4040: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4041: } else {
1.1172.2.23 raeburn 4042: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4043: if ($hidepriv) {
4044: my %coursehash=&coursedescription($udom.'_'.$uname);
4045: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4046: if ($user !~ /:/) {
4047: $nothide{join(':',split(/[\@]/,$user))} = 1;
4048: } else {
4049: $nothide{$user} = 1;
4050: }
4051: }
4052: }
1.858 raeburn 4053: }
1.400 www 4054: my %returnhash=();
4055: my $now=time;
1.999 raeburn 4056: my %privileged;
1.800 albertel 4057: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4058: my ($role,$tend,$tstart);
4059: if ($context eq 'userroles') {
1.1149 raeburn 4060: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4061: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4062: } else {
4063: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4064: }
1.400 www 4065: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4066: my $status = 'active';
1.939 raeburn 4067: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4068: $status = 'previous';
4069: }
4070: if (($tstart) && ($now<$tstart)) {
4071: $status = 'future';
4072: }
4073: if (ref($types) eq 'ARRAY') {
4074: if (!grep(/^\Q$status\E$/,@{$types})) {
4075: next;
4076: }
4077: } else {
4078: if ($status ne 'active') {
4079: next;
4080: }
4081: }
1.867 raeburn 4082: my ($rolecode,$username,$domain,$section,$area);
4083: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4084: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4085: (undef,$domain,$username,$section) = split(/\//,$area);
4086: } else {
4087: ($role,$username,$domain,$section) = split(/\:/,$entry);
4088: }
1.832 raeburn 4089: if (ref($roledoms) eq 'ARRAY') {
4090: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4091: next;
4092: }
4093: }
4094: if (ref($roles) eq 'ARRAY') {
4095: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4096: if ($role =~ /^cr\//) {
4097: if (!grep(/^cr$/,@{$roles})) {
4098: next;
4099: }
1.1104 raeburn 4100: } elsif ($role =~ /^gr\//) {
4101: if (!grep(/^gr$/,@{$roles})) {
4102: next;
4103: }
1.922 raeburn 4104: } else {
4105: next;
4106: }
1.832 raeburn 4107: }
1.867 raeburn 4108: }
1.937 raeburn 4109: if ($hidepriv) {
1.1172.2.23 raeburn 4110: my @privroles = ('dc','su');
1.999 raeburn 4111: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4112: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4113: } else {
1.1172.2.23 raeburn 4114: my $possdoms = [$domain];
4115: if (ref($roledoms) eq 'ARRAY') {
4116: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4117: }
1.1172.2.23 raeburn 4118: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4119: if (!$nothide{$username.':'.$domain}) {
4120: next;
4121: }
4122: }
1.937 raeburn 4123: }
4124: }
1.933 raeburn 4125: if ($withsec) {
4126: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4127: $tstart.':'.$tend;
4128: } else {
4129: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4130: }
1.832 raeburn 4131: }
1.373 www 4132: return %returnhash;
1.399 www 4133: }
4134:
4135: # ----------------------------------------------------- Frontpage Announcements
4136: #
4137: #
4138:
4139: sub postannounce {
4140: my ($server,$text)=@_;
1.844 albertel 4141: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4142: unless ($text=~/\w/) { $text=''; }
4143: return &reply('setannounce:'.&escape($text),$server);
4144: }
4145:
4146: sub getannounce {
1.448 albertel 4147:
4148: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4149: my $announcement='';
1.800 albertel 4150: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4151: close($fh);
1.399 www 4152: if ($announcement=~/\w/) {
4153: return
4154: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4155: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4156: } else {
4157: return '';
4158: }
4159: } else {
4160: return '';
4161: }
1.351 www 4162: }
1.353 www 4163:
4164: # ---------------------------------------------------------- Course ID routines
4165: # Deal with domain's nohist_courseid.db files
4166: #
4167:
4168: sub courseidput {
1.921 raeburn 4169: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4170: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4171: my $outcome;
4172: if ($caller eq 'timeonly') {
4173: my $cids = '';
4174: foreach my $item (keys(%$storehash)) {
4175: $cids.=&escape($item).'&';
4176: }
4177: $cids=~s/\&$//;
4178: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4179: $coursehome);
4180: } else {
4181: my $items = '';
4182: foreach my $item (keys(%$storehash)) {
4183: $items.= &escape($item).'='.
4184: &freeze_escape($$storehash{$item}).'&';
4185: }
4186: $items=~s/\&$//;
4187: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4188: $coursehome);
1.918 raeburn 4189: }
4190: if ($outcome eq 'unknown_cmd') {
4191: my $what;
4192: foreach my $cid (keys(%$storehash)) {
4193: $what .= &escape($cid).'=';
1.921 raeburn 4194: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4195: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4196: }
4197: $what =~ s/\:$/&/;
4198: }
4199: $what =~ s/\&$//;
4200: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4201: } else {
4202: return $outcome;
4203: }
1.353 www 4204: }
4205:
4206: sub courseiddump {
1.921 raeburn 4207: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4208: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4209: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 4210: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4211: $hasuniquecode)=@_;
1.918 raeburn 4212: my $as_hash = 1;
4213: my %returnhash;
4214: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4215: my %libserv = &all_library();
4216: foreach my $tryserver (keys(%libserv)) {
4217: if ( ( $hostidflag == 1
4218: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4219: || (!defined($hostidflag)) ) {
4220:
1.918 raeburn 4221: if (($domfilter eq '') ||
4222: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4223: my $rep;
4224: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4225: $rep = &LONCAPA::Lond::dump_course_id_handler(
4226: join(":", (&host_domain($tryserver), $sincefilter,
4227: &escape($descfilter), &escape($instcodefilter),
4228: &escape($ownerfilter), &escape($coursefilter),
4229: &escape($typefilter), &escape($regexp_ok),
4230: $as_hash, &escape($selfenrollonly),
4231: &escape($catfilter), $showhidden, $caller,
4232: &escape($cloner), &escape($cc_clone), $cloneonly,
4233: &escape($createdbefore), &escape($createdafter),
1.1172.2.38 raeburn 4234: &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1172.2.22 raeburn 4235: } else {
4236: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4237: $sincefilter.':'.&escape($descfilter).':'.
4238: &escape($instcodefilter).':'.&escape($ownerfilter).
4239: ':'.&escape($coursefilter).':'.&escape($typefilter).
4240: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4241: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4242: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4243: &escape($cc_clone).':'.$cloneonly.':'.
4244: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.38 raeburn 4245: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1172.2.22 raeburn 4246: $tryserver);
4247: }
4248:
1.918 raeburn 4249: my @pairs=split(/\&/,$rep);
4250: foreach my $item (@pairs) {
4251: my ($key,$value)=split(/\=/,$item,2);
4252: $key = &unescape($key);
4253: next if ($key =~ /^error: 2 /);
4254: my $result = &thaw_unescape($value);
4255: if (ref($result) eq 'HASH') {
4256: $returnhash{$key}=$result;
4257: } else {
1.921 raeburn 4258: my @responses = split(/:/,$value);
4259: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4260: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4261: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4262: }
1.1008 raeburn 4263: }
1.353 www 4264: }
4265: }
4266: }
4267: }
4268: return %returnhash;
4269: }
4270:
1.1055 raeburn 4271: sub courselastaccess {
4272: my ($cdom,$cnum,$hostidref) = @_;
4273: my %returnhash;
4274: if ($cdom && $cnum) {
4275: my $chome = &homeserver($cnum,$cdom);
4276: if ($chome ne 'no_host') {
4277: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4278: &extract_lastaccess(\%returnhash,$rep);
4279: }
4280: } else {
4281: if (!$cdom) { $cdom=''; }
4282: my %libserv = &all_library();
4283: foreach my $tryserver (keys(%libserv)) {
4284: if (ref($hostidref) eq 'ARRAY') {
4285: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4286: }
4287: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4288: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4289: &extract_lastaccess(\%returnhash,$rep);
4290: }
4291: }
4292: }
4293: return %returnhash;
4294: }
4295:
4296: sub extract_lastaccess {
4297: my ($returnhash,$rep) = @_;
4298: if (ref($returnhash) eq 'HASH') {
4299: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4300: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4301: $rep eq '') {
4302: my @pairs=split(/\&/,$rep);
4303: foreach my $item (@pairs) {
4304: my ($key,$value)=split(/\=/,$item,2);
4305: $key = &unescape($key);
4306: next if ($key =~ /^error: 2 /);
4307: $returnhash->{$key} = &thaw_unescape($value);
4308: }
4309: }
4310: }
4311: return;
4312: }
4313:
1.658 raeburn 4314: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4315:
4316: sub dcmailput {
1.685 raeburn 4317: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4318: my $status = &Apache::lonnet::critical(
1.740 www 4319: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4320: &escape($message),$server);
1.662 raeburn 4321: return $status;
4322: }
4323:
1.658 raeburn 4324: sub dcmaildump {
4325: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4326: my %returnhash=();
1.846 albertel 4327:
4328: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4329: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4330: &escape($enddate).':';
4331: my @esc_senders=map { &escape($_)} @$senders;
4332: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4333: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4334: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4335: if (($key) && ($value)) {
4336: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4337: }
4338: }
4339: }
4340: return %returnhash;
4341: }
1.662 raeburn 4342: # ---------------------------------------------------------- Domain roles
4343:
4344: sub get_domain_roles {
4345: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4346: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4347: $startdate = '.';
4348: }
1.1018 raeburn 4349: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4350: $enddate = '.';
4351: }
1.922 raeburn 4352: my $rolelist;
4353: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4354: $rolelist = join('&',@{$roles});
1.922 raeburn 4355: }
1.662 raeburn 4356: my %personnel = ();
1.841 albertel 4357:
4358: my %servers = &get_servers($dom,'library');
4359: foreach my $tryserver (keys(%servers)) {
4360: %{$personnel{$tryserver}}=();
4361: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4362: &escape($startdate).':'.
4363: &escape($enddate).':'.
4364: &escape($rolelist), $tryserver))) {
4365: my ($key,$value) = split(/\=/,$line,2);
4366: if (($key) && ($value)) {
4367: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4368: }
4369: }
1.662 raeburn 4370: }
4371: return %personnel;
4372: }
1.658 raeburn 4373:
1.1057 www 4374: # ----------------------------------------------------------- Interval timing
1.149 www 4375:
1.1153 www 4376: {
4377: # Caches needed for speedup of navmaps
4378: # We don't want to cache this for very long at all (5 seconds at most)
4379: #
4380: # The user for whom we cache
4381: my $cachedkey='';
4382: # The cached times for this user
4383: my %cachedtimes=();
4384: # When this was last done
4385: my $cachedtime=();
4386:
4387: sub load_all_first_access {
1.1154 raeburn 4388: my ($uname,$udom)=@_;
1.1156 www 4389: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 4390: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4391: return;
4392: }
4393: $cachedtime=time;
4394: $cachedkey=$uname.':'.$udom;
4395: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4396: }
4397:
1.504 albertel 4398: sub get_first_access {
1.1162 raeburn 4399: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4400: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4401: if ($argsymb) { $symb=$argsymb; }
4402: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4403: if ($argmap) { $map = $argmap; }
1.926 albertel 4404: if ($type eq 'course') {
4405: $res='course';
4406: } elsif ($type eq 'map') {
1.588 albertel 4407: $res=&symbread($map);
4408: } else {
4409: $res=$symb;
4410: }
1.1153 www 4411: &load_all_first_access($uname,$udom);
4412: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4413: }
4414:
4415: sub set_first_access {
1.1162 raeburn 4416: my ($type,$interval)=@_;
1.790 albertel 4417: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4418: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4419: if ($type eq 'course') {
4420: $res='course';
4421: } elsif ($type eq 'map') {
1.588 albertel 4422: $res=&symbread($map);
4423: } else {
4424: $res=$symb;
4425: }
1.1153 www 4426: $cachedkey='';
1.1162 raeburn 4427: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4428: if (!$firstaccess) {
1.1162 raeburn 4429: my $start = time;
4430: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4431: $udom,$uname);
4432: if ($putres eq 'ok') {
4433: &put('timerinterval',{"$courseid\0$res"=>$interval},
4434: $udom,$uname);
4435: &appenv(
4436: {
4437: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4438: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4439: }
4440: );
4441: }
4442: return $putres;
1.505 albertel 4443: }
4444: return 'already_set';
1.504 albertel 4445: }
1.1153 www 4446: }
1.1172.2.32 raeburn 4447:
4448: sub checkout {
4449: my ($symb,$tuname,$tudom,$tcrsid)=@_;
4450: my $now=time;
4451: my $lonhost=$perlvar{'lonHostID'};
4452: my $infostr=&escape(
4453: 'CHECKOUTTOKEN&'.
4454: $tuname.'&'.
4455: $tudom.'&'.
4456: $tcrsid.'&'.
4457: $symb.'&'.
4458: $now.'&'.$ENV{'REMOTE_ADDR'});
4459: my $token=&reply('tmpput:'.$infostr,$lonhost);
4460: if ($token=~/^error\:/) {
4461: &logthis("<font color=\"blue\">WARNING: ".
4462: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
4463: "</font>");
4464: return '';
4465: }
4466:
4467: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
4468: $token=~tr/a-z/A-Z/;
4469:
4470: my %infohash=('resource.0.outtoken' => $token,
4471: 'resource.0.checkouttime' => $now,
4472: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
4473:
4474: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4475: return '';
4476: } else {
4477: &logthis("<font color=\"blue\">WARNING: ".
4478: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
4479: "</font>");
4480: }
4481:
4482: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4483: &escape('Checkout '.$infostr.' - '.
4484: $token)) ne 'ok') {
4485: return '';
4486: } else {
4487: &logthis("<font color=\"blue\">WARNING: ".
4488: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
4489: "</font>");
4490: }
4491: return $token;
4492: }
4493:
4494: # ------------------------------------------------------------ Check in an item
4495:
4496: sub checkin {
4497: my $token=shift;
4498: my $now=time;
4499: my ($ta,$tb,$lonhost)=split(/\*/,$token);
4500: $lonhost=~tr/A-Z/a-z/;
4501: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
4502: $dtoken=~s/\W/\_/g;
4503: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
4504: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
4505:
4506: unless (($tuname) && ($tudom)) {
4507: &logthis('Check in '.$token.' ('.$dtoken.') failed');
4508: return '';
4509: }
4510:
4511: unless (&allowed('mgr',$tcrsid)) {
4512: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
4513: $env{'user.name'}.' - '.$env{'user.domain'});
4514: return '';
4515: }
4516:
4517: my %infohash=('resource.0.intoken' => $token,
4518: 'resource.0.checkintime' => $now,
4519: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
4520:
4521: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4522: return '';
4523: }
4524:
4525: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4526: &escape('Checkin - '.$token)) ne 'ok') {
4527: return '';
4528: }
4529:
4530: return ($symb,$tuname,$tudom,$tcrsid);
4531: }
4532:
1.110 www 4533: # --------------------------------------------- Set Expire Date for Spreadsheet
4534:
4535: sub expirespread {
4536: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4537: my $cid=$env{'request.course.id'};
1.110 www 4538: if ($cid) {
4539: my $now=time;
4540: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4541: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4542: $env{'course.'.$cid.'.num'}.
1.110 www 4543: ':nohist_expirationdates:'.
4544: &escape($key).'='.$now,
1.620 albertel 4545: $env{'course.'.$cid.'.home'})
1.110 www 4546: }
4547: return 'ok';
1.14 www 4548: }
4549:
1.109 www 4550: # ----------------------------------------------------- Devalidate Spreadsheets
4551:
4552: sub devalidate {
1.325 www 4553: my ($symb,$uname,$udom)=@_;
1.620 albertel 4554: my $cid=$env{'request.course.id'};
1.109 www 4555: if ($cid) {
1.391 matthew 4556: # delete the stored spreadsheets for
4557: # - the student level sheet of this user in course's homespace
4558: # - the assessment level sheet for this resource
4559: # for this user in user's homespace
1.553 albertel 4560: # - current conditional state info
1.325 www 4561: my $key=$uname.':'.$udom.':';
1.109 www 4562: my $status=
1.299 matthew 4563: &del('nohist_calculatedsheets',
1.391 matthew 4564: [$key.'studentcalc:'],
1.620 albertel 4565: $env{'course.'.$cid.'.domain'},
4566: $env{'course.'.$cid.'.num'})
1.133 albertel 4567: .' '.
4568: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4569: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4570: unless ($status eq 'ok ok') {
4571: &logthis('Could not devalidate spreadsheet '.
1.325 www 4572: $uname.' at '.$udom.' for '.
1.109 www 4573: $symb.': '.$status);
1.133 albertel 4574: }
1.553 albertel 4575: &delenv('user.state.'.$cid);
1.109 www 4576: }
4577: }
4578:
1.265 albertel 4579: sub get_scalar {
4580: my ($string,$end) = @_;
4581: my $value;
4582: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4583: $value = $1;
4584: } elsif ($$string =~ s/^([^&]*?)&//) {
4585: $value = $1;
4586: }
4587: return &unescape($value);
4588: }
4589:
4590: sub array2str {
4591: my (@array) = @_;
4592: my $result=&arrayref2str(\@array);
4593: $result=~s/^__ARRAY_REF__//;
4594: $result=~s/__END_ARRAY_REF__$//;
4595: return $result;
4596: }
4597:
1.204 albertel 4598: sub arrayref2str {
4599: my ($arrayref) = @_;
1.265 albertel 4600: my $result='__ARRAY_REF__';
1.204 albertel 4601: foreach my $elem (@$arrayref) {
1.265 albertel 4602: if(ref($elem) eq 'ARRAY') {
4603: $result.=&arrayref2str($elem).'&';
4604: } elsif(ref($elem) eq 'HASH') {
4605: $result.=&hashref2str($elem).'&';
4606: } elsif(ref($elem)) {
4607: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4608: } else {
4609: $result.=&escape($elem).'&';
4610: }
4611: }
4612: $result=~s/\&$//;
1.265 albertel 4613: $result .= '__END_ARRAY_REF__';
1.204 albertel 4614: return $result;
4615: }
4616:
1.168 albertel 4617: sub hash2str {
1.204 albertel 4618: my (%hash) = @_;
4619: my $result=&hashref2str(\%hash);
1.265 albertel 4620: $result=~s/^__HASH_REF__//;
4621: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4622: return $result;
4623: }
4624:
4625: sub hashref2str {
4626: my ($hashref)=@_;
1.265 albertel 4627: my $result='__HASH_REF__';
1.800 albertel 4628: foreach my $key (sort(keys(%$hashref))) {
4629: if (ref($key) eq 'ARRAY') {
4630: $result.=&arrayref2str($key).'=';
4631: } elsif (ref($key) eq 'HASH') {
4632: $result.=&hashref2str($key).'=';
4633: } elsif (ref($key)) {
1.265 albertel 4634: $result.='=';
1.800 albertel 4635: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4636: } else {
1.1132 raeburn 4637: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4638: }
4639:
1.800 albertel 4640: if(ref($hashref->{$key}) eq 'ARRAY') {
4641: $result.=&arrayref2str($hashref->{$key}).'&';
4642: } elsif(ref($hashref->{$key}) eq 'HASH') {
4643: $result.=&hashref2str($hashref->{$key}).'&';
4644: } elsif(ref($hashref->{$key})) {
1.265 albertel 4645: $result.='&';
1.800 albertel 4646: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4647: } else {
1.800 albertel 4648: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4649: }
4650: }
1.168 albertel 4651: $result=~s/\&$//;
1.265 albertel 4652: $result .= '__END_HASH_REF__';
1.168 albertel 4653: return $result;
4654: }
4655:
4656: sub str2hash {
1.265 albertel 4657: my ($string)=@_;
4658: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4659: return %$hash;
4660: }
4661:
4662: sub str2hashref {
1.168 albertel 4663: my ($string) = @_;
1.265 albertel 4664:
4665: my %hash;
4666:
4667: if($string !~ /^__HASH_REF__/) {
4668: if (! ($string eq '' || !defined($string))) {
4669: $hash{'error'}='Not hash reference';
4670: }
4671: return (\%hash, $string);
4672: }
4673:
4674: $string =~ s/^__HASH_REF__//;
4675:
4676: while($string !~ /^__END_HASH_REF__/) {
4677: #key
4678: my $key='';
4679: if($string =~ /^__HASH_REF__/) {
4680: ($key, $string)=&str2hashref($string);
4681: if(defined($key->{'error'})) {
4682: $hash{'error'}='Bad data';
4683: return (\%hash, $string);
4684: }
4685: } elsif($string =~ /^__ARRAY_REF__/) {
4686: ($key, $string)=&str2arrayref($string);
4687: if($key->[0] eq 'Array reference error') {
4688: $hash{'error'}='Bad data';
4689: return (\%hash, $string);
4690: }
4691: } else {
4692: $string =~ s/^(.*?)=//;
1.267 albertel 4693: $key=&unescape($1);
1.265 albertel 4694: }
4695: $string =~ s/^=//;
4696:
4697: #value
4698: my $value='';
4699: if($string =~ /^__HASH_REF__/) {
4700: ($value, $string)=&str2hashref($string);
4701: if(defined($value->{'error'})) {
4702: $hash{'error'}='Bad data';
4703: return (\%hash, $string);
4704: }
4705: } elsif($string =~ /^__ARRAY_REF__/) {
4706: ($value, $string)=&str2arrayref($string);
4707: if($value->[0] eq 'Array reference error') {
4708: $hash{'error'}='Bad data';
4709: return (\%hash, $string);
4710: }
4711: } else {
4712: $value=&get_scalar(\$string,'__END_HASH_REF__');
4713: }
4714: $string =~ s/^&//;
4715:
4716: $hash{$key}=$value;
1.204 albertel 4717: }
1.265 albertel 4718:
4719: $string =~ s/^__END_HASH_REF__//;
4720:
4721: return (\%hash, $string);
1.204 albertel 4722: }
4723:
4724: sub str2array {
1.265 albertel 4725: my ($string)=@_;
4726: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4727: return @$array;
4728: }
4729:
4730: sub str2arrayref {
1.204 albertel 4731: my ($string) = @_;
1.265 albertel 4732: my @array;
4733:
4734: if($string !~ /^__ARRAY_REF__/) {
4735: if (! ($string eq '' || !defined($string))) {
4736: $array[0]='Array reference error';
4737: }
4738: return (\@array, $string);
4739: }
4740:
4741: $string =~ s/^__ARRAY_REF__//;
4742:
4743: while($string !~ /^__END_ARRAY_REF__/) {
4744: my $value='';
4745: if($string =~ /^__HASH_REF__/) {
4746: ($value, $string)=&str2hashref($string);
4747: if(defined($value->{'error'})) {
4748: $array[0] ='Array reference error';
4749: return (\@array, $string);
4750: }
4751: } elsif($string =~ /^__ARRAY_REF__/) {
4752: ($value, $string)=&str2arrayref($string);
4753: if($value->[0] eq 'Array reference error') {
4754: $array[0] ='Array reference error';
4755: return (\@array, $string);
4756: }
4757: } else {
4758: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4759: }
4760: $string =~ s/^&//;
4761:
4762: push(@array, $value);
1.191 harris41 4763: }
1.265 albertel 4764:
4765: $string =~ s/^__END_ARRAY_REF__//;
4766:
4767: return (\@array, $string);
1.168 albertel 4768: }
4769:
1.167 albertel 4770: # -------------------------------------------------------------------Temp Store
4771:
1.168 albertel 4772: sub tmpreset {
4773: my ($symb,$namespace,$domain,$stuname) = @_;
4774: if (!$symb) {
4775: $symb=&symbread();
1.620 albertel 4776: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4777: }
4778: $symb=escape($symb);
4779:
1.620 albertel 4780: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4781: $namespace=~s/\//\_/g;
4782: $namespace=~s/\W//g;
4783:
1.620 albertel 4784: if (!$domain) { $domain=$env{'user.domain'}; }
4785: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4786: if ($domain eq 'public' && $stuname eq 'public') {
4787: $stuname=$ENV{'REMOTE_ADDR'};
4788: }
1.1117 foxr 4789: my $path=LONCAPA::tempdir();
1.168 albertel 4790: my %hash;
4791: if (tie(%hash,'GDBM_File',
4792: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4793: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4794: foreach my $key (keys(%hash)) {
1.180 albertel 4795: if ($key=~ /:$symb/) {
1.168 albertel 4796: delete($hash{$key});
4797: }
4798: }
4799: }
4800: }
4801:
1.167 albertel 4802: sub tmpstore {
1.168 albertel 4803: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4804:
4805: if (!$symb) {
4806: $symb=&symbread();
1.620 albertel 4807: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4808: }
4809: $symb=escape($symb);
4810:
4811: if (!$namespace) {
4812: # I don't think we would ever want to store this for a course.
4813: # it seems this will only be used if we don't have a course.
1.620 albertel 4814: #$namespace=$env{'request.course.id'};
1.168 albertel 4815: #if (!$namespace) {
1.620 albertel 4816: $namespace=$env{'request.state'};
1.168 albertel 4817: #}
4818: }
4819: $namespace=~s/\//\_/g;
4820: $namespace=~s/\W//g;
1.620 albertel 4821: if (!$domain) { $domain=$env{'user.domain'}; }
4822: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4823: if ($domain eq 'public' && $stuname eq 'public') {
4824: $stuname=$ENV{'REMOTE_ADDR'};
4825: }
1.168 albertel 4826: my $now=time;
4827: my %hash;
1.1117 foxr 4828: my $path=LONCAPA::tempdir();
1.168 albertel 4829: if (tie(%hash,'GDBM_File',
4830: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4831: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4832: $hash{"version:$symb"}++;
4833: my $version=$hash{"version:$symb"};
4834: my $allkeys='';
4835: foreach my $key (keys(%$storehash)) {
4836: $allkeys.=$key.':';
1.591 albertel 4837: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4838: }
4839: $hash{"$version:$symb:timestamp"}=$now;
4840: $allkeys.='timestamp';
4841: $hash{"$version:keys:$symb"}=$allkeys;
4842: if (untie(%hash)) {
4843: return 'ok';
4844: } else {
4845: return "error:$!";
4846: }
4847: } else {
4848: return "error:$!";
4849: }
4850: }
1.167 albertel 4851:
1.168 albertel 4852: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4853:
1.168 albertel 4854: sub tmprestore {
4855: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4856:
1.168 albertel 4857: if (!$symb) {
4858: $symb=&symbread();
1.620 albertel 4859: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4860: }
4861: $symb=escape($symb);
4862:
1.620 albertel 4863: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4864:
1.620 albertel 4865: if (!$domain) { $domain=$env{'user.domain'}; }
4866: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4867: if ($domain eq 'public' && $stuname eq 'public') {
4868: $stuname=$ENV{'REMOTE_ADDR'};
4869: }
1.168 albertel 4870: my %returnhash;
4871: $namespace=~s/\//\_/g;
4872: $namespace=~s/\W//g;
4873: my %hash;
1.1117 foxr 4874: my $path=LONCAPA::tempdir();
1.168 albertel 4875: if (tie(%hash,'GDBM_File',
4876: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4877: &GDBM_READER(),0640)) {
1.168 albertel 4878: my $version=$hash{"version:$symb"};
4879: $returnhash{'version'}=$version;
4880: my $scope;
4881: for ($scope=1;$scope<=$version;$scope++) {
4882: my $vkeys=$hash{"$scope:keys:$symb"};
4883: my @keys=split(/:/,$vkeys);
4884: my $key;
4885: $returnhash{"$scope:keys"}=$vkeys;
4886: foreach $key (@keys) {
1.591 albertel 4887: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4888: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4889: }
4890: }
1.168 albertel 4891: if (!(untie(%hash))) {
4892: return "error:$!";
4893: }
4894: } else {
4895: return "error:$!";
4896: }
4897: return %returnhash;
1.167 albertel 4898: }
4899:
1.9 www 4900: # ----------------------------------------------------------------------- Store
4901:
4902: sub store {
1.124 www 4903: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4904: my $home='';
4905:
1.168 albertel 4906: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4907:
1.213 www 4908: $symb=&symbclean($symb);
1.122 albertel 4909: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4910:
1.620 albertel 4911: if (!$domain) { $domain=$env{'user.domain'}; }
4912: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4913:
4914: &devalidate($symb,$stuname,$domain);
1.109 www 4915:
4916: $symb=escape($symb);
1.187 www 4917: if (!$namespace) {
1.620 albertel 4918: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4919: return '';
4920: }
4921: }
1.620 albertel 4922: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4923:
4924: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4925: $$storehash{'host'}=$perlvar{'lonHostID'};
4926:
1.12 www 4927: my $namevalue='';
1.800 albertel 4928: foreach my $key (keys(%$storehash)) {
4929: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4930: }
1.12 www 4931: $namevalue=~s/\&$//;
1.187 www 4932: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4933: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4934: }
4935:
1.47 www 4936: # -------------------------------------------------------------- Critical Store
4937:
4938: sub cstore {
1.124 www 4939: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4940: my $home='';
4941:
1.168 albertel 4942: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4943:
1.213 www 4944: $symb=&symbclean($symb);
1.122 albertel 4945: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4946:
1.620 albertel 4947: if (!$domain) { $domain=$env{'user.domain'}; }
4948: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4949:
4950: &devalidate($symb,$stuname,$domain);
1.109 www 4951:
4952: $symb=escape($symb);
1.187 www 4953: if (!$namespace) {
1.620 albertel 4954: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4955: return '';
4956: }
4957: }
1.620 albertel 4958: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4959:
4960: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4961: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4962:
1.47 www 4963: my $namevalue='';
1.800 albertel 4964: foreach my $key (keys(%$storehash)) {
4965: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4966: }
1.47 www 4967: $namevalue=~s/\&$//;
1.187 www 4968: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4969: return critical
4970: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4971: }
4972:
1.9 www 4973: # --------------------------------------------------------------------- Restore
4974:
4975: sub restore {
1.124 www 4976: my ($symb,$namespace,$domain,$stuname) = @_;
4977: my $home='';
4978:
1.168 albertel 4979: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4980:
1.122 albertel 4981: if (!$symb) {
1.1172.2.26 raeburn 4982: return if ($namespace eq 'courserequests');
4983: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4984: } else {
1.1172.2.26 raeburn 4985: unless ($namespace eq 'courserequests') {
4986: $symb=&escape(&symbclean($symb));
4987: }
1.122 albertel 4988: }
1.188 www 4989: if (!$namespace) {
1.620 albertel 4990: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4991: return '';
4992: }
4993: }
1.620 albertel 4994: if (!$domain) { $domain=$env{'user.domain'}; }
4995: if (!$stuname) { $stuname=$env{'user.name'}; }
4996: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4997: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4998:
1.12 www 4999: my %returnhash=();
1.800 albertel 5000: foreach my $line (split(/\&/,$answer)) {
5001: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5002: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5003: }
1.75 www 5004: my $version;
5005: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5006: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5007: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5008: }
1.75 www 5009: }
1.13 www 5010: return %returnhash;
1.34 www 5011: }
5012:
5013: # ---------------------------------------------------------- Course Description
1.1118 foxr 5014: #
5015: #
1.34 www 5016:
5017: sub coursedescription {
1.731 albertel 5018: my ($courseid,$args)=@_;
1.34 www 5019: $courseid=~s/^\///;
1.49 www 5020: $courseid=~s/\_/\//g;
1.34 www 5021: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5022: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5023: my $normalid=$cdomain.'_'.$cnum;
5024: # need to always cache even if we get errors otherwise we keep
5025: # trying and trying and trying to get the course description.
5026: my %envhash=();
5027: my %returnhash=();
1.731 albertel 5028:
5029: my $expiretime=600;
5030: if ($env{'request.course.id'} eq $normalid) {
5031: $expiretime=120;
5032: }
5033:
5034: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5035: if (!$args->{'freshen_cache'}
5036: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5037: foreach my $key (keys(%env)) {
5038: next if ($key !~ /^\Q$prefix\E(.*)/);
5039: my ($setting) = $1;
5040: $returnhash{$setting} = $env{$key};
5041: }
5042: return %returnhash;
5043: }
5044:
1.1118 foxr 5045: # get the data again
5046:
1.731 albertel 5047: if (!$args->{'one_time'}) {
5048: $envhash{'course.'.$normalid.'.last_cache'}=time;
5049: }
1.811 albertel 5050:
1.34 www 5051: if ($chome ne 'no_host') {
1.302 albertel 5052: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5053: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5054: my $username = $env{'user.name'}; # Defult username
5055: if(defined $args->{'user'}) {
5056: $username = $args->{'user'};
5057: }
1.129 albertel 5058: $returnhash{'home'}= $chome;
5059: $returnhash{'domain'} = $cdomain;
5060: $returnhash{'num'} = $cnum;
1.741 raeburn 5061: if (!defined($returnhash{'type'})) {
5062: $returnhash{'type'} = 'Course';
5063: }
1.130 albertel 5064: while (my ($name,$value) = each %returnhash) {
1.53 www 5065: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5066: }
1.270 www 5067: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5068: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5069: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5070: $envhash{'course.'.$normalid.'.home'}=$chome;
5071: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5072: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5073: }
5074: }
1.731 albertel 5075: if (!$args->{'one_time'}) {
1.949 raeburn 5076: &appenv(\%envhash);
1.731 albertel 5077: }
1.302 albertel 5078: return %returnhash;
1.461 www 5079: }
5080:
1.1080 raeburn 5081: sub update_released_required {
5082: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5083: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5084: $cid = $env{'request.course.id'};
5085: $cdom = $env{'course.'.$cid.'.domain'};
5086: $cnum = $env{'course.'.$cid.'.num'};
5087: $chome = $env{'course.'.$cid.'.home'};
5088: }
5089: if ($needsrelease) {
5090: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5091: my $needsupdate;
5092: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5093: $needsupdate = 1;
5094: } else {
5095: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5096: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5097: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5098: $needsupdate = 1;
5099: }
5100: }
5101: if ($needsupdate) {
5102: my %needshash = (
5103: 'internal.releaserequired' => $needsrelease,
5104: );
5105: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5106: if ($putresult eq 'ok') {
5107: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5108: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5109: if (ref($crsinfo{$cid}) eq 'HASH') {
5110: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5111: &courseidput($cdom,\%crsinfo,$chome,'notime');
5112: }
5113: }
5114: }
5115: }
5116: return;
5117: }
5118:
1.461 www 5119: # -------------------------------------------------See if a user is privileged
5120:
5121: sub privileged {
1.1172.2.23 raeburn 5122: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5123: my $now = time;
1.1172.2.23 raeburn 5124: my $roles;
5125: if (ref($possroles) eq 'ARRAY') {
5126: $roles = $possroles;
5127: } else {
5128: $roles = ['dc','su'];
5129: }
5130: if (ref($possdomains) eq 'ARRAY') {
5131: my %privileged = &privileged_by_domain($possdomains,$roles);
5132: foreach my $dom (@{$possdomains}) {
5133: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5134: (ref($privileged{$dom}) eq 'HASH')) {
5135: foreach my $role (@{$roles}) {
5136: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5137: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5138: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5139: return 1 unless (($end && $end < $now) ||
5140: ($start && $start > $now));
5141: }
5142: }
5143: }
5144: }
5145: }
5146: } else {
5147: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5148: my $now = time;
1.1170 droeschl 5149:
1.1172.2.23 raeburn 5150: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170 droeschl 5151: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5152: if (grep(/^\Q$trole\E$/,@{$roles})) {
5153: return 1 unless ($tend && $tend < $now)
5154: or ($tstart && $tstart > $now);
1.1170 droeschl 5155: }
1.1172.2.23 raeburn 5156: }
5157: }
1.461 www 5158: return 0;
1.9 www 5159: }
1.1 albertel 5160:
1.1172.2.23 raeburn 5161: sub privileged_by_domain {
5162: my ($domains,$roles) = @_;
5163: my %privileged = ();
5164: my $cachetime = 60*60*24;
5165: my $now = time;
5166: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5167: return %privileged;
5168: }
5169: foreach my $dom (@{$domains}) {
5170: next if (ref($privileged{$dom}) eq 'HASH');
5171: my $needroles;
5172: foreach my $role (@{$roles}) {
5173: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5174: if (defined($cached)) {
5175: if (ref($result) eq 'HASH') {
5176: $privileged{$dom}{$role} = $result;
5177: }
5178: } else {
5179: $needroles = 1;
5180: }
5181: }
5182: if ($needroles) {
5183: my %dompersonnel = &get_domain_roles($dom,$roles);
5184: $privileged{$dom} = {};
5185: foreach my $server (keys(%dompersonnel)) {
5186: if (ref($dompersonnel{$server}) eq 'HASH') {
5187: foreach my $item (keys(%{$dompersonnel{$server}})) {
5188: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5189: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5190: next if ($end && $end < $now);
5191: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5192: $dompersonnel{$server}{$item};
5193: }
5194: }
5195: }
5196: if (ref($privileged{$dom}) eq 'HASH') {
5197: foreach my $role (@{$roles}) {
5198: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5199: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5200: } else {
5201: my %hash = ();
5202: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5203: }
5204: }
5205: }
5206: }
5207: }
5208: return %privileged;
5209: }
5210:
1.103 harris41 5211: # -------------------------------------------------------- Get user privileges
1.11 www 5212:
5213: sub rolesinit {
1.1169 droeschl 5214: my ($domain, $username) = @_;
5215: my %userroles = ('user.login.time' => time);
5216: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5217:
5218: # firstaccess and timerinterval are related to timed maps/resources.
5219: # also, blocking can be triggered by an activating timer
5220: # it's saved in the user's %env.
5221: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5222: my %timerinterval = &dump('timerinterval', $domain, $username);
5223: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5224: %timerintchk, %timerintenv);
5225:
1.1162 raeburn 5226: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5227: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5228: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5229: }
1.1169 droeschl 5230:
1.1162 raeburn 5231: foreach my $key (keys(%timerinterval)) {
5232: my ($cid,$rest) = split(/\0/,$key);
5233: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5234: }
1.1169 droeschl 5235:
1.11 www 5236: my %allroles=();
1.1162 raeburn 5237: my %allgroups=();
1.11 www 5238:
1.1169 droeschl 5239: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5240: my $role = $rolesdump{$area};
5241: $area =~ s/\_\w\w$//;
5242:
5243: my ($trole, $tend, $tstart, $group_privs);
5244:
5245: if ($role =~ /^cr/) {
5246: # Custom role, defined by a user
5247: # e.g., user.role.cr/msu/smith/mynewrole
5248: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5249: $trole = $1;
5250: ($tend, $tstart) = split('_', $2);
5251: } else {
5252: $trole = $role;
5253: }
5254: } elsif ($role =~ m|^gr/|) {
5255: # Role of member in a group, defined within a course/community
5256: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5257: ($trole, $tend, $tstart) = split(/_/, $role);
5258: next if $tstart eq '-1';
5259: ($trole, $group_privs) = split(/\//, $trole);
5260: $group_privs = &unescape($group_privs);
5261: } else {
5262: # Just a normal role, defined in roles.tab
5263: ($trole, $tend, $tstart) = split(/_/,$role);
5264: }
5265:
5266: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5267: $username);
5268: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5269:
5270: # role expired or not available yet?
5271: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5272: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5273:
5274: next if $area eq '' or $trole eq '';
5275:
5276: my $spec = "$trole.$area";
5277: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5278:
5279: if ($trole =~ /^cr\//) {
5280: # Custom role, defined by a user
5281: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5282: } elsif ($trole eq 'gr') {
5283: # Role of a member in a group, defined within a course/community
5284: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5285: next;
5286: } else {
5287: # Normal role, defined in roles.tab
5288: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5289: }
5290:
5291: my $cid = $tdomain.'_'.$trest;
5292: unless ($firstaccchk{$cid}) {
5293: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5294: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5295: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5296: $coursetimerstarts{$cid}{$item};
5297: }
5298: }
5299: $firstaccchk{$cid} = 1;
5300: }
5301: unless ($timerintchk{$cid}) {
5302: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5303: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5304: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5305: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5306: }
1.12 www 5307: }
1.1169 droeschl 5308: $timerintchk{$cid} = 1;
1.191 harris41 5309: }
1.11 www 5310: }
1.1169 droeschl 5311:
5312: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5313: \%allroles, \%allgroups);
5314: $env{'user.adv'} = $userroles{'user.adv'};
5315:
1.1162 raeburn 5316: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5317: }
5318:
1.567 raeburn 5319: sub set_arearole {
1.1172.2.19 raeburn 5320: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5321: unless ($nolog) {
1.567 raeburn 5322: # log the associated role with the area
1.1172.2.19 raeburn 5323: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5324: }
1.743 albertel 5325: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5326: }
5327:
5328: sub custom_roleprivs {
5329: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5330: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 5331: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5332: if (&hostname($homsvr) ne '') {
1.567 raeburn 5333: my ($rdummy,$roledef)=
5334: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5335: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5336: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5337: if (defined($syspriv)) {
1.1043 raeburn 5338: if ($trest =~ /^$match_community$/) {
5339: $syspriv =~ s/bre\&S//;
5340: }
1.567 raeburn 5341: $$allroles{'cm./'}.=':'.$syspriv;
5342: $$allroles{$spec.'./'}.=':'.$syspriv;
5343: }
5344: if ($tdomain ne '') {
5345: if (defined($dompriv)) {
5346: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5347: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5348: }
5349: if (($trest ne '') && (defined($coursepriv))) {
5350: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5351: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5352: }
5353: }
5354: }
5355: }
5356: }
5357:
1.678 raeburn 5358: sub group_roleprivs {
5359: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5360: my $access = 1;
5361: my $now = time;
5362: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5363: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5364: if ($access) {
1.811 albertel 5365: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5366: $$allgroups{$course}{$group} .=':'.$group_privs;
5367: }
5368: }
1.567 raeburn 5369:
5370: sub standard_roleprivs {
5371: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5372: if (defined($pr{$trole.':s'})) {
5373: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5374: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5375: }
5376: if ($tdomain ne '') {
5377: if (defined($pr{$trole.':d'})) {
5378: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5379: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5380: }
5381: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5382: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5383: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5384: }
5385: }
5386: }
5387:
5388: sub set_userprivs {
1.1064 raeburn 5389: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5390: my $author=0;
5391: my $adv=0;
1.678 raeburn 5392: my %grouproles = ();
5393: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5394: my @groupkeys;
1.1000 raeburn 5395: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5396: push(@groupkeys,$role);
5397: }
5398: if (ref($groups_roles) eq 'HASH') {
5399: foreach my $key (keys(%{$groups_roles})) {
5400: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5401: push(@groupkeys,$key);
5402: }
5403: }
5404: }
5405: if (@groupkeys > 0) {
5406: foreach my $role (@groupkeys) {
5407: my ($trole,$area,$sec,$extendedarea);
5408: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5409: $trole = $1;
5410: $area = $2;
5411: $sec = $3;
5412: $extendedarea = $area.$sec;
5413: if (exists($$allgroups{$area})) {
5414: foreach my $group (keys(%{$$allgroups{$area}})) {
5415: my $spec = $trole.'.'.$extendedarea;
5416: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5417: $$allgroups{$area}{$group};
1.1064 raeburn 5418: }
1.678 raeburn 5419: }
5420: }
5421: }
5422: }
5423: }
1.800 albertel 5424: foreach my $group (keys(%grouproles)) {
5425: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5426: }
1.800 albertel 5427: foreach my $role (keys(%{$allroles})) {
5428: my %thesepriv;
1.941 raeburn 5429: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5430: foreach my $item (split(/:/,$$allroles{$role})) {
5431: if ($item ne '') {
5432: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5433: if ($restrictions eq '') {
5434: $thesepriv{$privilege}='F';
5435: } elsif ($thesepriv{$privilege} ne 'F') {
5436: $thesepriv{$privilege}.=$restrictions;
5437: }
5438: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5439: }
5440: }
5441: my $thesestr='';
1.1104 raeburn 5442: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5443: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5444: }
5445: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5446: }
5447: return ($author,$adv);
5448: }
5449:
1.994 raeburn 5450: sub role_status {
1.1104 raeburn 5451: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5452: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 5453: my ($one,$two) = split(m{\./},$rolekey,2);
5454: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5455: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 5456: $$where = '/'.$two;
1.994 raeburn 5457: $$trolecode=$$role.'.'.$$where;
5458: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5459: $$tstatus='is';
1.1104 raeburn 5460: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5461: $$tstatus='future';
1.1034 raeburn 5462: if ($$tstart<$now) {
5463: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5464: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5465: my (%allroles,%allgroups,$group_privs,
5466: %groups_roles,@rolecodes);
1.1002 raeburn 5467: my %userroles = (
5468: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5469: );
1.1064 raeburn 5470: @rolecodes = ('cm');
1.1002 raeburn 5471: my $spec=$$role.'.'.$$where;
5472: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5473: if ($$role =~ /^cr\//) {
5474: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5475: push(@rolecodes,'cr');
1.1002 raeburn 5476: } elsif ($$role eq 'gr') {
1.1064 raeburn 5477: push(@rolecodes,$$role);
1.1002 raeburn 5478: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5479: $env{'user.name'});
1.1064 raeburn 5480: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5481: (undef,my $group_privs) = split(/\//,$trole);
5482: $group_privs = &unescape($group_privs);
5483: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5484: 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 5485: &get_groups_roles($tdomain,$trest,
5486: \%course_roles,\@rolecodes,
5487: \%groups_roles);
1.1002 raeburn 5488: } else {
1.1064 raeburn 5489: push(@rolecodes,$$role);
1.1002 raeburn 5490: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5491: }
1.1064 raeburn 5492: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5493: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5494: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5495: }
5496: }
1.1034 raeburn 5497: $$tstatus = 'is';
1.1002 raeburn 5498: }
1.994 raeburn 5499: }
5500: if ($$tend) {
1.1104 raeburn 5501: if ($$tend<$update) {
1.994 raeburn 5502: $$tstatus='expired';
5503: } elsif ($$tend<$now) {
5504: $$tstatus='will_not';
5505: }
5506: }
5507: }
5508: }
5509: }
5510:
1.1104 raeburn 5511: sub get_groups_roles {
5512: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5513: return unless((ref($cdom_courseroles) eq 'HASH') &&
5514: (ref($rolecodes) eq 'ARRAY') &&
5515: (ref($groups_roles) eq 'HASH'));
5516: if (keys(%{$cdom_courseroles}) > 0) {
5517: my ($cnum) = ($rest =~ /^($match_courseid)/);
5518: if ($cdom ne '' && $cnum ne '') {
5519: foreach my $key (keys(%{$cdom_courseroles})) {
5520: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5521: my $crsrole = $1;
5522: my $crssec = $2;
5523: if ($crsrole =~ /^cr/) {
5524: unless (grep(/^cr$/,@{$rolecodes})) {
5525: push(@{$rolecodes},'cr');
5526: }
5527: } else {
5528: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5529: push(@{$rolecodes},$crsrole);
5530: }
5531: }
5532: my $rolekey = "$crsrole./$cdom/$cnum";
5533: if ($crssec ne '') {
5534: $rolekey .= "/$crssec";
5535: }
5536: $rolekey .= './';
5537: $groups_roles->{$rolekey} = $rolecodes;
5538: }
5539: }
5540: }
5541: }
5542: return;
5543: }
5544:
5545: sub delete_env_groupprivs {
5546: my ($where,$courseroles,$possroles) = @_;
5547: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5548: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5549: unless (ref($courseroles->{$udom}) eq 'HASH') {
5550: %{$courseroles->{$udom}} =
5551: &get_my_roles('','','userroles',['active'],
5552: $possroles,[$udom],1);
5553: }
5554: if (ref($courseroles->{$udom}) eq 'HASH') {
5555: foreach my $item (keys(%{$courseroles->{$udom}})) {
5556: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5557: my $area = '/'.$cdom.'/'.$cnum;
5558: my $privkey = "user.priv.$crsrole.$area";
5559: if ($crssec ne '') {
5560: $privkey .= '/'.$crssec;
5561: }
5562: $privkey .= ".$area/$group";
5563: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5564: }
5565: }
5566: return;
5567: }
5568:
1.994 raeburn 5569: sub check_adhoc_privs {
1.1104 raeburn 5570: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5571: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9 raeburn 5572: my $setprivs;
1.994 raeburn 5573: if ($env{$cckey}) {
5574: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5575: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5576: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5577: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5578: $setprivs = 1;
1.994 raeburn 5579: }
5580: } else {
1.1088 raeburn 5581: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5582: $setprivs = 1;
1.994 raeburn 5583: }
1.1172.2.9 raeburn 5584: return $setprivs;
1.994 raeburn 5585: }
5586:
5587: sub set_adhoc_privileges {
5588: # role can be cc or ca
1.1088 raeburn 5589: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5590: my $area = '/'.$dcdom.'/'.$pickedcourse;
5591: my $spec = $role.'.'.$area;
5592: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 5593: $env{'user.name'},1);
1.994 raeburn 5594: my %ccrole = ();
5595: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5596: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5597: &appenv(\%userroles,[$role,'cm']);
5598: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5599: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5600: &appenv( {'request.role' => $spec,
5601: 'request.role.domain' => $dcdom,
5602: 'request.course.sec' => ''
5603: }
5604: );
5605: my $tadv=0;
5606: if (&allowed('adv') eq 'F') { $tadv=1; }
5607: &appenv({'request.role.adv' => $tadv});
5608: }
1.994 raeburn 5609: }
5610:
1.12 www 5611: # --------------------------------------------------------------- get interface
5612:
5613: sub get {
1.131 albertel 5614: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5615: my $items='';
1.800 albertel 5616: foreach my $item (@$storearr) {
5617: $items.=&escape($item).'&';
1.191 harris41 5618: }
1.12 www 5619: $items=~s/\&$//;
1.620 albertel 5620: if (!$udomain) { $udomain=$env{'user.domain'}; }
5621: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5622: my $uhome=&homeserver($uname,$udomain);
5623:
1.133 albertel 5624: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5625: my @pairs=split(/\&/,$rep);
1.273 albertel 5626: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5627: return @pairs;
5628: }
1.15 www 5629: my %returnhash=();
1.42 www 5630: my $i=0;
1.800 albertel 5631: foreach my $item (@$storearr) {
5632: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5633: $i++;
1.191 harris41 5634: }
1.15 www 5635: return %returnhash;
1.27 www 5636: }
5637:
5638: # --------------------------------------------------------------- del interface
5639:
5640: sub del {
1.133 albertel 5641: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5642: my $items='';
1.800 albertel 5643: foreach my $item (@$storearr) {
5644: $items.=&escape($item).'&';
1.191 harris41 5645: }
1.984 neumanie 5646:
1.27 www 5647: $items=~s/\&$//;
1.620 albertel 5648: if (!$udomain) { $udomain=$env{'user.domain'}; }
5649: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5650: my $uhome=&homeserver($uname,$udomain);
5651: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5652: }
5653:
5654: # -------------------------------------------------------------- dump interface
5655:
1.1172.2.22 raeburn 5656: sub unserialize {
5657: my ($rep, $escapedkeys) = @_;
5658:
5659: return {} if $rep =~ /^error/;
5660:
5661: my %returnhash=();
5662: foreach my $item (split(/\&/,$rep)) {
5663: my ($key, $value) = split(/=/, $item, 2);
5664: $key = unescape($key) unless $escapedkeys;
5665: next if $key =~ /^error: 2 /;
5666: $returnhash{$key} = &thaw_unescape($value);
5667: }
5668: return \%returnhash;
5669: }
5670:
5671: # see Lond::dump_with_regexp
5672: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5673: sub dump {
1.1172.2.22 raeburn 5674: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5675: if (!$udomain) { $udomain=$env{'user.domain'}; }
5676: if (!$uname) { $uname=$env{'user.name'}; }
5677: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5678:
1.1172.2.22 raeburn 5679: my $reply;
5680: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
5681: # user is hosted on this machine
5682: $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 5683: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 5684: return %{&unserialize($reply, $escapedkeys)};
5685: }
1.755 albertel 5686: if ($regexp) {
5687: $regexp=&escape($regexp);
5688: } else {
5689: $regexp='.';
5690: }
1.1166 raeburn 5691: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5692: my @pairs=split(/\&/,$rep);
5693: my %returnhash=();
1.1098 foxr 5694: if (!($rep =~ /^error/ )) {
5695: foreach my $item (@pairs) {
5696: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 5697: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 5698: next if ($key =~ /^error: 2 /);
5699: $returnhash{$key}=&thaw_unescape($value);
5700: }
1.755 albertel 5701: }
5702: return %returnhash;
1.407 www 5703: }
5704:
1.1098 foxr 5705:
1.717 albertel 5706: # --------------------------------------------------------- dumpstore interface
5707:
5708: sub dumpstore {
5709: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 5710: # same as dump but keys must be escaped. They may contain colon separated
5711: # lists of values that may themself contain colons (e.g. symbs).
5712: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5713: }
5714:
1.407 www 5715: # -------------------------------------------------------------- keys interface
5716:
5717: sub getkeys {
5718: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5719: if (!$udomain) { $udomain=$env{'user.domain'}; }
5720: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5721: my $uhome=&homeserver($uname,$udomain);
5722: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5723: my @keyarray=();
1.800 albertel 5724: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5725: next if ($key =~ /^error: 2 /);
1.800 albertel 5726: push(@keyarray,&unescape($key));
1.407 www 5727: }
5728: return @keyarray;
1.318 matthew 5729: }
5730:
1.319 matthew 5731: # --------------------------------------------------------------- currentdump
5732: sub currentdump {
1.328 matthew 5733: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5734: $courseid = $env{'request.course.id'} if (! defined($courseid));
5735: $sdom = $env{'user.domain'} if (! defined($sdom));
5736: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5737: my $uhome = &homeserver($sname,$sdom);
5738: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 5739: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5740: #
1.318 matthew 5741: my %returnhash=();
1.319 matthew 5742: #
5743: if ($rep eq "unknown_cmd") {
5744: # an old lond will not know currentdump
5745: # Do a dump and make it look like a currentdump
1.822 albertel 5746: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5747: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5748: my %hash = @tmp;
5749: @tmp=();
1.424 matthew 5750: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5751: } else {
5752: my @pairs=split(/\&/,$rep);
1.800 albertel 5753: foreach my $pair (@pairs) {
5754: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5755: my ($symb,$param) = split(/:/,$key);
5756: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5757: &thaw_unescape($value);
1.319 matthew 5758: }
1.191 harris41 5759: }
1.12 www 5760: return %returnhash;
1.424 matthew 5761: }
5762:
5763: sub convert_dump_to_currentdump{
5764: my %hash = %{shift()};
5765: my %returnhash;
5766: # Code ripped from lond, essentially. The only difference
5767: # here is the unescaping done by lonnet::dump(). Conceivably
5768: # we might run in to problems with parameter names =~ /^v\./
5769: while (my ($key,$value) = each(%hash)) {
5770: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5771: $symb = &unescape($symb);
5772: $param = &unescape($param);
1.424 matthew 5773: next if ($v eq 'version' || $symb eq 'keys');
5774: next if (exists($returnhash{$symb}) &&
5775: exists($returnhash{$symb}->{$param}) &&
5776: $returnhash{$symb}->{'v.'.$param} > $v);
5777: $returnhash{$symb}->{$param}=$value;
5778: $returnhash{$symb}->{'v.'.$param}=$v;
5779: }
5780: #
5781: # Remove all of the keys in the hashes which keep track of
5782: # the version of the parameter.
5783: while (my ($symb,$param_hash) = each(%returnhash)) {
5784: # use a foreach because we are going to delete from the hash.
5785: foreach my $key (keys(%$param_hash)) {
5786: delete($param_hash->{$key}) if ($key =~ /^v\./);
5787: }
5788: }
5789: return \%returnhash;
1.12 www 5790: }
5791:
1.627 albertel 5792: # ------------------------------------------------------ critical inc interface
5793:
5794: sub cinc {
5795: return &inc(@_,'critical');
5796: }
5797:
1.449 matthew 5798: # --------------------------------------------------------------- inc interface
5799:
5800: sub inc {
1.627 albertel 5801: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5802: if (!$udomain) { $udomain=$env{'user.domain'}; }
5803: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5804: my $uhome=&homeserver($uname,$udomain);
5805: my $items='';
5806: if (! ref($store)) {
5807: # got a single value, so use that instead
5808: $items = &escape($store).'=&';
5809: } elsif (ref($store) eq 'SCALAR') {
5810: $items = &escape($$store).'=&';
5811: } elsif (ref($store) eq 'ARRAY') {
5812: $items = join('=&',map {&escape($_);} @{$store});
5813: } elsif (ref($store) eq 'HASH') {
5814: while (my($key,$value) = each(%{$store})) {
5815: $items.= &escape($key).'='.&escape($value).'&';
5816: }
5817: }
5818: $items=~s/\&$//;
1.627 albertel 5819: if ($critical) {
5820: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5821: } else {
5822: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5823: }
1.449 matthew 5824: }
5825:
1.12 www 5826: # --------------------------------------------------------------- put interface
5827:
5828: sub put {
1.134 albertel 5829: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5830: if (!$udomain) { $udomain=$env{'user.domain'}; }
5831: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5832: my $uhome=&homeserver($uname,$udomain);
1.12 www 5833: my $items='';
1.800 albertel 5834: foreach my $item (keys(%$storehash)) {
5835: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5836: }
1.12 www 5837: $items=~s/\&$//;
1.134 albertel 5838: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5839: }
5840:
1.631 albertel 5841: # ------------------------------------------------------------ newput interface
5842:
5843: sub newput {
5844: my ($namespace,$storehash,$udomain,$uname)=@_;
5845: if (!$udomain) { $udomain=$env{'user.domain'}; }
5846: if (!$uname) { $uname=$env{'user.name'}; }
5847: my $uhome=&homeserver($uname,$udomain);
5848: my $items='';
5849: foreach my $key (keys(%$storehash)) {
5850: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5851: }
5852: $items=~s/\&$//;
5853: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5854: }
5855:
5856: # --------------------------------------------------------- putstore interface
5857:
1.524 raeburn 5858: sub putstore {
1.715 albertel 5859: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5860: if (!$udomain) { $udomain=$env{'user.domain'}; }
5861: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5862: my $uhome=&homeserver($uname,$udomain);
5863: my $items='';
1.715 albertel 5864: foreach my $key (keys(%$storehash)) {
5865: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5866: }
1.715 albertel 5867: $items=~s/\&$//;
1.716 albertel 5868: my $esc_symb=&escape($symb);
5869: my $esc_v=&escape($version);
1.715 albertel 5870: my $reply =
1.716 albertel 5871: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5872: $uhome);
5873: if ($reply eq 'unknown_cmd') {
1.716 albertel 5874: # gfall back to way things use to be done
1.715 albertel 5875: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5876: $uname);
1.524 raeburn 5877: }
1.715 albertel 5878: return $reply;
5879: }
5880:
5881: sub old_putstore {
1.716 albertel 5882: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5883: if (!$udomain) { $udomain=$env{'user.domain'}; }
5884: if (!$uname) { $uname=$env{'user.name'}; }
5885: my $uhome=&homeserver($uname,$udomain);
5886: my %newstorehash;
1.800 albertel 5887: foreach my $item (keys(%$storehash)) {
5888: my $key = $version.':'.&escape($symb).':'.$item;
5889: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5890: }
5891: my $items='';
5892: my %allitems = ();
1.800 albertel 5893: foreach my $item (keys(%newstorehash)) {
5894: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5895: my $key = $1.':keys:'.$2;
5896: $allitems{$key} .= $3.':';
5897: }
1.800 albertel 5898: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5899: }
1.800 albertel 5900: foreach my $item (keys(%allitems)) {
5901: $allitems{$item} =~ s/\:$//;
5902: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5903: }
5904: $items=~s/\&$//;
5905: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5906: }
5907:
1.47 www 5908: # ------------------------------------------------------ critical put interface
5909:
5910: sub cput {
1.134 albertel 5911: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5912: if (!$udomain) { $udomain=$env{'user.domain'}; }
5913: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5914: my $uhome=&homeserver($uname,$udomain);
1.47 www 5915: my $items='';
1.800 albertel 5916: foreach my $item (keys(%$storehash)) {
5917: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5918: }
1.47 www 5919: $items=~s/\&$//;
1.134 albertel 5920: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5921: }
5922:
5923: # -------------------------------------------------------------- eget interface
5924:
5925: sub eget {
1.133 albertel 5926: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5927: my $items='';
1.800 albertel 5928: foreach my $item (@$storearr) {
5929: $items.=&escape($item).'&';
1.191 harris41 5930: }
1.12 www 5931: $items=~s/\&$//;
1.620 albertel 5932: if (!$udomain) { $udomain=$env{'user.domain'}; }
5933: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5934: my $uhome=&homeserver($uname,$udomain);
5935: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5936: my @pairs=split(/\&/,$rep);
5937: my %returnhash=();
1.42 www 5938: my $i=0;
1.800 albertel 5939: foreach my $item (@$storearr) {
5940: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5941: $i++;
1.191 harris41 5942: }
1.12 www 5943: return %returnhash;
5944: }
5945:
1.667 albertel 5946: # ------------------------------------------------------------ tmpput interface
5947: sub tmpput {
1.802 raeburn 5948: my ($storehash,$server,$context)=@_;
1.667 albertel 5949: my $items='';
1.800 albertel 5950: foreach my $item (keys(%$storehash)) {
5951: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5952: }
5953: $items=~s/\&$//;
1.802 raeburn 5954: if (defined($context)) {
5955: $items .= ':'.&escape($context);
5956: }
1.667 albertel 5957: return &reply("tmpput:$items",$server);
5958: }
5959:
5960: # ------------------------------------------------------------ tmpget interface
5961: sub tmpget {
1.688 albertel 5962: my ($token,$server)=@_;
5963: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5964: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5965: my %returnhash;
5966: foreach my $item (split(/\&/,$rep)) {
5967: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5968: next if ($key =~ /^error: 2 /);
1.667 albertel 5969: $returnhash{&unescape($key)}=&thaw_unescape($value);
5970: }
5971: return %returnhash;
5972: }
5973:
1.1113 raeburn 5974: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5975: sub tmpdel {
5976: my ($token,$server)=@_;
5977: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5978: return &reply("tmpdel:$token",$server);
5979: }
5980:
1.1172.2.13 raeburn 5981: # ------------------------------------------------------------ get_timebased_id
5982:
5983: sub get_timebased_id {
5984: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5985: $maxtries) = @_;
5986: my ($newid,$error,$dellock);
5987: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5988: return ('','ok','invalid call to get suffix');
5989: }
5990:
5991: # set defaults for any optional args for which values were not supplied
5992: if ($who eq '') {
5993: $who = $env{'user.name'}.':'.$env{'user.domain'};
5994: }
5995: if (!$locktries) {
5996: $locktries = 3;
5997: }
5998: if (!$maxtries) {
5999: $maxtries = 10;
6000: }
6001:
6002: if (($cdom eq '') || ($cnum eq '')) {
6003: if ($env{'request.course.id'}) {
6004: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6005: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6006: }
6007: if (($cdom eq '') || ($cnum eq '')) {
6008: return ('','ok','call to get suffix not in course context');
6009: }
6010: }
6011:
6012: # construct locking item
6013: my $lockhash = {
6014: $prefix."\0".'locked_'.$keyid => $who,
6015: };
6016: my $tries = 0;
6017:
6018: # attempt to get lock on nohist_$namespace file
6019: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6020: while (($gotlock ne 'ok') && $tries <$locktries) {
6021: $tries ++;
6022: sleep 1;
6023: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6024: }
6025:
6026: # attempt to get unique identifier, based on current timestamp
6027: if ($gotlock eq 'ok') {
6028: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6029: my $id = time;
6030: $newid = $id;
6031: my $idtries = 0;
6032: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6033: if ($idtype eq 'concat') {
6034: $newid = $id.$idtries;
6035: } else {
6036: $newid ++;
6037: }
6038: $idtries ++;
6039: }
6040: if (!exists($inuse{$prefix."\0".$newid})) {
6041: my %new_item = (
6042: $prefix."\0".$newid => $who,
6043: );
6044: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6045: $cdom,$cnum);
6046: if ($putresult ne 'ok') {
6047: undef($newid);
6048: $error = 'error saving new item: '.$putresult;
6049: }
6050: } else {
6051: $error = ('error: no unique suffix available for the new item ');
6052: }
6053: # remove lock
6054: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6055: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6056: } else {
6057: $error = "error: could not obtain lockfile\n";
6058: $dellock = 'ok';
6059: }
6060: return ($newid,$dellock,$error);
6061: }
6062:
1.765 albertel 6063: # -------------------------------------------------- portfolio access checking
6064:
6065: sub portfolio_access {
1.766 albertel 6066: my ($requrl) = @_;
1.765 albertel 6067: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6068: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 6069: if ($result) {
6070: my %setters;
6071: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6072: my ($startblock,$endblock) =
6073: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6074: if ($startblock && $endblock) {
6075: return 'B';
6076: }
6077: } else {
6078: my ($startblock,$endblock) =
6079: &Apache::loncommon::blockcheck(\%setters,'port');
6080: if ($startblock && $endblock) {
6081: return 'B';
6082: }
6083: }
6084: }
1.765 albertel 6085: if ($result eq 'ok') {
1.766 albertel 6086: return 'F';
1.765 albertel 6087: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6088: return 'A';
1.765 albertel 6089: }
1.766 albertel 6090: return '';
1.765 albertel 6091: }
6092:
6093: sub get_portfolio_access {
1.767 albertel 6094: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
6095:
6096: if (!ref($access_hash)) {
6097: my $current_perms = &get_portfile_permissions($udom,$unum);
6098: my %access_controls = &get_access_controls($current_perms,$group,
6099: $file_name);
6100: $access_hash = $access_controls{$file_name};
6101: }
6102:
1.765 albertel 6103: my ($public,$guest,@domains,@users,@courses,@groups);
6104: my $now = time;
6105: if (ref($access_hash) eq 'HASH') {
6106: foreach my $key (keys(%{$access_hash})) {
6107: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6108: if ($start > $now) {
6109: next;
6110: }
6111: if ($end && $end<$now) {
6112: next;
6113: }
6114: if ($scope eq 'public') {
6115: $public = $key;
6116: last;
6117: } elsif ($scope eq 'guest') {
6118: $guest = $key;
6119: } elsif ($scope eq 'domains') {
6120: push(@domains,$key);
6121: } elsif ($scope eq 'users') {
6122: push(@users,$key);
6123: } elsif ($scope eq 'course') {
6124: push(@courses,$key);
6125: } elsif ($scope eq 'group') {
6126: push(@groups,$key);
6127: }
6128: }
6129: if ($public) {
6130: return 'ok';
6131: }
6132: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6133: if ($guest) {
6134: return $guest;
6135: }
6136: } else {
6137: if (@domains > 0) {
6138: foreach my $domkey (@domains) {
6139: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6140: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6141: return 'ok';
6142: }
6143: }
6144: }
6145: }
6146: if (@users > 0) {
6147: foreach my $userkey (@users) {
1.865 raeburn 6148: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6149: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6150: if (ref($item) eq 'HASH') {
6151: if (($item->{'uname'} eq $env{'user.name'}) &&
6152: ($item->{'udom'} eq $env{'user.domain'})) {
6153: return 'ok';
6154: }
6155: }
6156: }
6157: }
1.765 albertel 6158: }
6159: }
6160: my %roleshash;
6161: my @courses_and_groups = @courses;
6162: push(@courses_and_groups,@groups);
6163: if (@courses_and_groups > 0) {
6164: my (%allgroups,%allroles);
6165: my ($start,$end,$role,$sec,$group);
6166: foreach my $envkey (%env) {
1.1060 raeburn 6167: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6168: my $cid = $2.'_'.$3;
6169: if ($1 eq 'gr') {
6170: $group = $4;
6171: $allgroups{$cid}{$group} = $env{$envkey};
6172: } else {
6173: if ($4 eq '') {
6174: $sec = 'none';
6175: } else {
6176: $sec = $4;
6177: }
6178: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6179: }
1.811 albertel 6180: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6181: my $cid = $2.'_'.$3;
6182: if ($4 eq '') {
6183: $sec = 'none';
6184: } else {
6185: $sec = $4;
6186: }
6187: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6188: }
6189: }
6190: if (keys(%allroles) == 0) {
6191: return;
6192: }
6193: foreach my $key (@courses_and_groups) {
6194: my %content = %{$$access_hash{$key}};
6195: my $cnum = $content{'number'};
6196: my $cdom = $content{'domain'};
6197: my $cid = $cdom.'_'.$cnum;
6198: if (!exists($allroles{$cid})) {
6199: next;
6200: }
6201: foreach my $role_id (keys(%{$content{'roles'}})) {
6202: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6203: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6204: my @status = @{$content{'roles'}{$role_id}{'access'}};
6205: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6206: foreach my $role (keys(%{$allroles{$cid}})) {
6207: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6208: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6209: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6210: if (grep/^all$/,@sections) {
6211: return 'ok';
6212: } else {
6213: if (grep/^$sec$/,@sections) {
6214: return 'ok';
6215: }
6216: }
6217: }
6218: }
6219: if (keys(%{$allgroups{$cid}}) == 0) {
6220: if (grep/^none$/,@groups) {
6221: return 'ok';
6222: }
6223: } else {
6224: if (grep/^all$/,@groups) {
6225: return 'ok';
6226: }
6227: foreach my $group (keys(%{$allgroups{$cid}})) {
6228: if (grep/^$group$/,@groups) {
6229: return 'ok';
6230: }
6231: }
6232: }
6233: }
6234: }
6235: }
6236: }
6237: }
6238: if ($guest) {
6239: return $guest;
6240: }
6241: }
6242: }
6243: return;
6244: }
6245:
6246: sub course_group_datechecker {
6247: my ($dates,$now,$status) = @_;
6248: my ($start,$end) = split(/\./,$dates);
6249: if (!$start && !$end) {
6250: return 'ok';
6251: }
6252: if (grep/^active$/,@{$status}) {
6253: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6254: return 'ok';
6255: }
6256: }
6257: if (grep/^previous$/,@{$status}) {
6258: if ($end > $now ) {
6259: return 'ok';
6260: }
6261: }
6262: if (grep/^future$/,@{$status}) {
6263: if ($start > $now) {
6264: return 'ok';
6265: }
6266: }
6267: return;
6268: }
6269:
6270: sub parse_portfolio_url {
6271: my ($url) = @_;
6272:
6273: my ($type,$udom,$unum,$group,$file_name);
6274:
1.823 albertel 6275: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6276: $type = 1;
6277: $udom = $1;
6278: $unum = $2;
6279: $file_name = $3;
1.823 albertel 6280: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6281: $type = 2;
6282: $udom = $1;
6283: $unum = $2;
6284: $group = $3;
6285: $file_name = $3.'/'.$4;
6286: }
6287: if (wantarray) {
6288: return ($type,$udom,$unum,$file_name,$group);
6289: }
6290: return $type;
6291: }
6292:
6293: sub is_portfolio_url {
6294: my ($url) = @_;
6295: return scalar(&parse_portfolio_url($url));
6296: }
6297:
1.798 raeburn 6298: sub is_portfolio_file {
6299: my ($file) = @_;
1.820 raeburn 6300: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6301: return 1;
6302: }
6303: return;
6304: }
6305:
1.976 raeburn 6306: sub usertools_access {
1.1084 raeburn 6307: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6308: my ($access,%tools);
6309: if ($context eq '') {
6310: $context = 'tools';
6311: }
6312: if ($context eq 'requestcourses') {
6313: %tools = (
6314: official => 1,
6315: unofficial => 1,
1.1006 raeburn 6316: community => 1,
1.1172.2.37 raeburn 6317: textbook => 1,
1.985 raeburn 6318: );
1.1172.2.9 raeburn 6319: } elsif ($context eq 'requestauthor') {
6320: %tools = (
6321: requestauthor => 1,
6322: );
1.985 raeburn 6323: } else {
6324: %tools = (
6325: aboutme => 1,
6326: blog => 1,
1.1172.2.6 raeburn 6327: webdav => 1,
1.985 raeburn 6328: portfolio => 1,
6329: );
6330: }
1.976 raeburn 6331: return if (!defined($tools{$tool}));
6332:
1.1172.2.35 raeburn 6333: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6334: $udom = $env{'user.domain'};
6335: $uname = $env{'user.name'};
6336: }
6337:
1.978 raeburn 6338: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6339: if ($action ne 'reload') {
1.985 raeburn 6340: if ($context eq 'requestcourses') {
6341: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6342: } elsif ($context eq 'requestauthor') {
6343: return $env{'environment.canrequest.author'};
1.985 raeburn 6344: } else {
6345: return $env{'environment.availabletools.'.$tool};
6346: }
6347: }
1.976 raeburn 6348: }
6349:
1.1172.2.9 raeburn 6350: my ($toolstatus,$inststatus,$envkey);
6351: if ($context eq 'requestauthor') {
6352: $envkey = $context;
6353: } else {
6354: $envkey = $context.'.'.$tool;
6355: }
1.976 raeburn 6356:
1.985 raeburn 6357: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6358: ($action ne 'reload')) {
1.1172.2.9 raeburn 6359: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6360: $inststatus = $env{'environment.inststatus'};
6361: } else {
1.1084 raeburn 6362: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6363: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6364: $inststatus = $userenvref->{'inststatus'};
6365: } else {
1.1172.2.9 raeburn 6366: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6367: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6368: $inststatus = $userenv{'inststatus'};
6369: }
1.976 raeburn 6370: }
6371:
6372: if ($toolstatus ne '') {
6373: if ($toolstatus) {
6374: $access = 1;
6375: } else {
6376: $access = 0;
6377: }
6378: return $access;
6379: }
6380:
1.1084 raeburn 6381: my ($is_adv,%domdef);
6382: if (ref($is_advref) eq 'HASH') {
6383: $is_adv = $is_advref->{'is_adv'};
6384: } else {
6385: $is_adv = &is_advanced_user($udom,$uname);
6386: }
6387: if (ref($domdefref) eq 'HASH') {
6388: %domdef = %{$domdefref};
6389: } else {
6390: %domdef = &get_domain_defaults($udom);
6391: }
1.976 raeburn 6392: if (ref($domdef{$tool}) eq 'HASH') {
6393: if ($is_adv) {
6394: if ($domdef{$tool}{'_LC_adv'} ne '') {
6395: if ($domdef{$tool}{'_LC_adv'}) {
6396: $access = 1;
6397: } else {
6398: $access = 0;
6399: }
6400: return $access;
6401: }
6402: }
6403: if ($inststatus ne '') {
6404: my ($hasaccess,$hasnoaccess);
6405: foreach my $affiliation (split(/:/,$inststatus)) {
6406: if ($domdef{$tool}{$affiliation} ne '') {
6407: if ($domdef{$tool}{$affiliation}) {
6408: $hasaccess = 1;
6409: } else {
6410: $hasnoaccess = 1;
6411: }
6412: }
6413: }
6414: if ($hasaccess || $hasnoaccess) {
6415: if ($hasaccess) {
6416: $access = 1;
6417: } elsif ($hasnoaccess) {
6418: $access = 0;
6419: }
6420: return $access;
6421: }
6422: } else {
6423: if ($domdef{$tool}{'default'} ne '') {
6424: if ($domdef{$tool}{'default'}) {
6425: $access = 1;
6426: } elsif ($domdef{$tool}{'default'} == 0) {
6427: $access = 0;
6428: }
6429: return $access;
6430: }
6431: }
6432: } else {
1.1172.2.6 raeburn 6433: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6434: $access = 1;
6435: } else {
6436: $access = 0;
6437: }
1.976 raeburn 6438: return $access;
6439: }
6440: }
6441:
1.1050 raeburn 6442: sub is_course_owner {
6443: my ($cdom,$cnum,$udom,$uname) = @_;
6444: if (($udom eq '') || ($uname eq '')) {
6445: $udom = $env{'user.domain'};
6446: $uname = $env{'user.name'};
6447: }
6448: unless (($udom eq '') || ($uname eq '')) {
6449: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6450: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6451: return 1;
6452: } else {
6453: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6454: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6455: return 1;
6456: }
6457: }
6458: }
6459: }
6460: return;
6461: }
6462:
1.976 raeburn 6463: sub is_advanced_user {
6464: my ($udom,$uname) = @_;
1.1085 raeburn 6465: if ($udom ne '' && $uname ne '') {
6466: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6467: if (wantarray) {
6468: return ($env{'user.adv'},$env{'user.author'});
6469: } else {
6470: return $env{'user.adv'};
6471: }
1.1085 raeburn 6472: }
6473: }
1.976 raeburn 6474: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6475: my %allroles;
1.1128 raeburn 6476: my ($is_adv,$is_author);
1.976 raeburn 6477: foreach my $role (keys(%roleshash)) {
6478: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6479: my $area = '/'.$tdomain.'/'.$trest;
6480: if ($sec ne '') {
6481: $area .= '/'.$sec;
6482: }
6483: if (($area ne '') && ($trole ne '')) {
6484: my $spec=$trole.'.'.$area;
6485: if ($trole =~ /^cr\//) {
6486: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6487: } elsif ($trole ne 'gr') {
6488: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6489: }
1.1128 raeburn 6490: if ($trole eq 'au') {
6491: $is_author = 1;
6492: }
1.976 raeburn 6493: }
6494: }
6495: foreach my $role (keys(%allroles)) {
6496: last if ($is_adv);
6497: foreach my $item (split(/:/,$allroles{$role})) {
6498: if ($item ne '') {
6499: my ($privilege,$restrictions)=split(/&/,$item);
6500: if ($privilege eq 'adv') {
6501: $is_adv = 1;
6502: last;
6503: }
6504: }
6505: }
6506: }
1.1128 raeburn 6507: if (wantarray) {
6508: return ($is_adv,$is_author);
6509: }
1.976 raeburn 6510: return $is_adv;
6511: }
1.798 raeburn 6512:
1.1035 raeburn 6513: sub check_can_request {
1.1036 raeburn 6514: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6515: my $canreq = 0;
6516: my ($types,$typename) = &Apache::loncommon::course_types();
6517: my @options = ('approval','validate','autolimit');
6518: my $optregex = join('|',@options);
6519: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6520: foreach my $type (@{$types}) {
6521: if (&usertools_access($env{'user.name'},
6522: $env{'user.domain'},
6523: $type,undef,'requestcourses')) {
6524: $canreq ++;
1.1036 raeburn 6525: if (ref($request_domains) eq 'HASH') {
6526: push(@{$request_domains->{$type}},$env{'user.domain'});
6527: }
1.1035 raeburn 6528: if ($dom eq $env{'user.domain'}) {
6529: $can_request->{$type} = 1;
6530: }
6531: }
6532: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6533: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6534: if (@curr > 0) {
1.1036 raeburn 6535: foreach my $item (@curr) {
6536: if (ref($request_domains) eq 'HASH') {
6537: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6538: if ($otherdom ne '') {
6539: if (ref($request_domains->{$type}) eq 'ARRAY') {
6540: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6541: push(@{$request_domains->{$type}},$otherdom);
6542: }
6543: } else {
6544: push(@{$request_domains->{$type}},$otherdom);
6545: }
6546: }
6547: }
6548: }
6549: unless($dom eq $env{'user.domain'}) {
6550: $canreq ++;
1.1035 raeburn 6551: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6552: $can_request->{$type} = 1;
6553: }
6554: }
6555: }
6556: }
6557: }
6558: }
6559: return $canreq;
6560: }
6561:
1.341 www 6562: # ---------------------------------------------- Custom access rule evaluation
6563:
6564: sub customaccess {
6565: my ($priv,$uri)=@_;
1.807 albertel 6566: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6567: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6568: $udom = &LONCAPA::clean_domain($udom);
6569: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6570: my $access=0;
1.800 albertel 6571: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6572: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6573: if ($type eq 'user') {
6574: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6575: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6576: if ($tdom) {
6577: if ($tdom ne $env{'user.domain'}) { next; }
6578: }
1.896 albertel 6579: if ($tuname) {
6580: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6581: }
6582: $access=($effect eq 'allow');
6583: last;
6584: }
6585: } else {
6586: if ($role) {
6587: if ($role ne $urole) { next; }
6588: }
6589: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6590: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6591: if ($tdom) {
6592: if ($tdom ne $udom) { next; }
6593: }
6594: if ($tcrs) {
6595: if ($tcrs ne $ucrs) { next; }
6596: }
6597: if ($tsec) {
6598: if ($tsec ne $usec) { next; }
6599: }
6600: $access=($effect eq 'allow');
6601: last;
6602: }
6603: if ($realm eq '' && $role eq '') {
6604: $access=($effect eq 'allow');
6605: }
1.402 bowersj2 6606: }
1.341 www 6607: }
6608: return $access;
6609: }
6610:
1.103 harris41 6611: # ------------------------------------------------- Check for a user privilege
1.12 www 6612:
6613: sub allowed {
1.810 raeburn 6614: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6615: my $ver_orguri=$uri;
1.439 www 6616: $uri=&deversion($uri);
1.152 www 6617: my $orguri=$uri;
1.52 www 6618: $uri=&declutter($uri);
1.809 raeburn 6619:
1.810 raeburn 6620: if ($priv eq 'evb') {
6621: # Evade communication block restrictions for specified role in a course
6622: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6623: return $1;
6624: } else {
6625: return;
6626: }
6627: }
6628:
1.620 albertel 6629: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6630: # Free bre access to adm and meta resources
1.775 albertel 6631: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6632: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6633: && ($priv eq 'bre')) {
1.14 www 6634: return 'F';
1.159 www 6635: }
6636:
1.545 banghart 6637: # Free bre access to user's own portfolio contents
1.714 raeburn 6638: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6639: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6640: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6641: my %setters;
6642: my ($startblock,$endblock) =
6643: &Apache::loncommon::blockcheck(\%setters,'port');
6644: if ($startblock && $endblock) {
6645: return 'B';
6646: } else {
6647: return 'F';
6648: }
1.545 banghart 6649: }
6650:
1.762 raeburn 6651: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6652: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6653: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6654: if (exists($env{'request.course.id'})) {
6655: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6656: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6657: if (($domain eq $cdom) && ($name eq $cnum)) {
6658: my $courseprivid=$env{'request.course.id'};
6659: $courseprivid=~s/\_/\//;
6660: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6661: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6662: return $1;
1.762 raeburn 6663: } else {
6664: if ($env{'request.course.sec'}) {
6665: $courseprivid.='/'.$env{'request.course.sec'};
6666: }
6667: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6668: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6669: return $2;
6670: }
1.714 raeburn 6671: }
6672: }
6673: }
6674: }
6675:
1.159 www 6676: # Free bre to public access
6677:
6678: if ($priv eq 'bre') {
1.238 www 6679: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6680: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6681: return 'F';
6682: }
1.238 www 6683: if ($copyright eq 'priv') {
6684: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6685: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6686: return '';
6687: }
6688: }
6689: if ($copyright eq 'domain') {
6690: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6691: unless (($env{'user.domain'} eq $1) ||
6692: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6693: return '';
6694: }
1.262 matthew 6695: }
1.620 albertel 6696: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6697: # Library role, so allow browsing of resources in this domain.
6698: return 'F';
1.238 www 6699: }
1.341 www 6700: if ($copyright eq 'custom') {
6701: unless (&customaccess($priv,$uri)) { return ''; }
6702: }
1.14 www 6703: }
1.264 matthew 6704: # Domain coordinator is trying to create a course
1.620 albertel 6705: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6706: # uri is the requested domain in this case.
6707: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6708: # a role of dc for the domain in question.
1.620 albertel 6709: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6710: }
1.29 www 6711:
1.52 www 6712: my $thisallowed='';
6713: my $statecond=0;
6714: my $courseprivid='';
6715:
1.1039 raeburn 6716: my $ownaccess;
1.1043 raeburn 6717: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6718: if (($priv eq 'bro') && ($env{'user.author'})) {
6719: if ($uri eq '') {
6720: $ownaccess = 1;
6721: } else {
6722: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6723: my $udom = $env{'user.domain'};
6724: my $uname = $env{'user.name'};
6725: if ($uri =~ m{^\Q$udom\E/?$}) {
6726: $ownaccess = 1;
1.1040 raeburn 6727: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6728: unless ($uri =~ m{\.\./}) {
6729: $ownaccess = 1;
6730: }
6731: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6732: my $now = time;
6733: if ($uri =~ m{^([^/]+)/?$}) {
6734: my $adom = $1;
6735: foreach my $key (keys(%env)) {
1.1042 raeburn 6736: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6737: my ($start,$end) = split('.',$env{$key});
6738: if (($now >= $start) && (!$end || $end < $now)) {
6739: $ownaccess = 1;
6740: last;
6741: }
6742: }
6743: }
6744: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6745: my $adom = $1;
6746: my $aname = $2;
1.1042 raeburn 6747: foreach my $role ('ca','aa') {
6748: if ($env{"user.role.$role./$adom/$aname"}) {
6749: my ($start,$end) =
6750: split('.',$env{"user.role.$role./$adom/$aname"});
6751: if (($now >= $start) && (!$end || $end < $now)) {
6752: $ownaccess = 1;
6753: last;
6754: }
1.1039 raeburn 6755: }
6756: }
6757: }
6758: }
6759: }
6760: }
6761: }
6762:
1.52 www 6763: # Course
6764:
1.620 albertel 6765: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6766: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6767: $thisallowed.=$1;
6768: }
1.52 www 6769: }
1.29 www 6770:
1.52 www 6771: # Domain
6772:
1.620 albertel 6773: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6774: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6775: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6776: $thisallowed.=$1;
6777: }
1.12 www 6778: }
1.52 www 6779:
1.1141 raeburn 6780: # User who is not author or co-author might still be able to edit
6781: # resource of an author in the domain (e.g., if Domain Coordinator).
6782: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6783: (&allowed('mdc',$env{'request.course.id'}))) {
6784: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6785: $thisallowed.=$1;
6786: }
6787: }
6788:
1.52 www 6789: # Course: uri itself is a course
1.66 www 6790: my $courseuri=$uri;
6791: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6792: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6793:
1.620 albertel 6794: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6795: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6796: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6797: $thisallowed.=$1;
6798: }
1.12 www 6799: }
1.29 www 6800:
1.665 albertel 6801: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6802: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6803: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6804: $thisallowed='';
1.671 raeburn 6805: my ($match)=&is_on_map($uri);
6806: if ($match) {
6807: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6808: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6809: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6810: if (@blockers > 0) {
6811: $thisallowed = 'B';
6812: } else {
6813: $thisallowed.=$1;
6814: }
1.671 raeburn 6815: }
6816: } else {
1.705 albertel 6817: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6818: if ($refuri) {
6819: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6820: $thisallowed='F';
1.671 raeburn 6821: } else {
6822: $refuri=&declutter($refuri);
6823: my ($match) = &is_on_map($refuri);
6824: if ($match) {
1.1162 raeburn 6825: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6826: if (@blockers > 0) {
6827: $thisallowed = 'B';
6828: } else {
6829: $thisallowed='F';
6830: }
1.671 raeburn 6831: }
1.669 raeburn 6832: }
1.671 raeburn 6833: }
6834: }
1.314 www 6835: }
1.492 albertel 6836:
1.766 albertel 6837: if ($priv eq 'bre'
6838: && $thisallowed ne 'F'
6839: && $thisallowed ne '2'
6840: && &is_portfolio_url($uri)) {
6841: $thisallowed = &portfolio_access($uri);
6842: }
6843:
1.52 www 6844: # Full access at system, domain or course-wide level? Exit.
1.29 www 6845: if ($thisallowed=~/F/) {
6846: return 'F';
6847: }
6848:
1.52 www 6849: # If this is generating or modifying users, exit with special codes
1.29 www 6850:
1.643 www 6851: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6852: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6853: my ($audom,$auname)=split('/',$uri);
1.643 www 6854: # no author name given, so this just checks on the general right to make a co-author in this domain
6855: unless ($auname) { return $thisallowed; }
6856: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6857: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6858: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6859: ($audom ne $env{'request.role.domain'}))) { return ''; }
6860: }
1.52 www 6861: return $thisallowed;
6862: }
6863: #
1.103 harris41 6864: # Gathered so far: system, domain and course wide privileges
1.52 www 6865: #
6866: # Course: See if uri or referer is an individual resource that is part of
6867: # the course
6868:
1.620 albertel 6869: if ($env{'request.course.id'}) {
1.232 www 6870:
1.620 albertel 6871: $courseprivid=$env{'request.course.id'};
6872: if ($env{'request.course.sec'}) {
6873: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6874: }
6875: $courseprivid=~s/\_/\//;
6876: my $checkreferer=1;
1.232 www 6877: my ($match,$cond)=&is_on_map($uri);
6878: if ($match) {
6879: $statecond=$cond;
1.620 albertel 6880: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6881: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6882: my $value = $1;
6883: if ($priv eq 'bre') {
6884: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6885: if (@blockers > 0) {
6886: $thisallowed = 'B';
6887: } else {
6888: $thisallowed.=$value;
6889: }
6890: } else {
6891: $thisallowed.=$value;
6892: }
1.52 www 6893: $checkreferer=0;
6894: }
1.29 www 6895: }
1.83 www 6896:
1.148 www 6897: if ($checkreferer) {
1.620 albertel 6898: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6899: unless ($refuri) {
1.800 albertel 6900: foreach my $key (keys(%env)) {
6901: if ($key=~/^httpref\..*\*/) {
6902: my $pattern=$key;
1.156 www 6903: $pattern=~s/^httpref\.\/res\///;
1.148 www 6904: $pattern=~s/\*/\[\^\/\]\+/g;
6905: $pattern=~s/\//\\\//g;
1.152 www 6906: if ($orguri=~/$pattern/) {
1.800 albertel 6907: $refuri=$env{$key};
1.148 www 6908: }
6909: }
1.191 harris41 6910: }
1.148 www 6911: }
1.232 www 6912:
1.148 www 6913: if ($refuri) {
1.152 www 6914: $refuri=&declutter($refuri);
1.232 www 6915: my ($match,$cond)=&is_on_map($refuri);
6916: if ($match) {
6917: my $refstatecond=$cond;
1.620 albertel 6918: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6919: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6920: my $value = $1;
6921: if ($priv eq 'bre') {
6922: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6923: if (@blockers > 0) {
6924: $thisallowed = 'B';
6925: } else {
6926: $thisallowed.=$value;
6927: }
6928: } else {
6929: $thisallowed.=$value;
6930: }
1.53 www 6931: $uri=$refuri;
6932: $statecond=$refstatecond;
1.52 www 6933: }
6934: }
1.148 www 6935: }
1.29 www 6936: }
1.52 www 6937: }
1.29 www 6938:
1.52 www 6939: #
1.103 harris41 6940: # Gathered now: all privileges that could apply, and condition number
1.52 www 6941: #
6942: #
6943: # Full or no access?
6944: #
1.29 www 6945:
1.52 www 6946: if ($thisallowed=~/F/) {
6947: return 'F';
6948: }
1.29 www 6949:
1.52 www 6950: unless ($thisallowed) {
6951: return '';
6952: }
1.29 www 6953:
1.52 www 6954: # Restrictions exist, deal with them
6955: #
6956: # C:according to course preferences
6957: # R:according to resource settings
6958: # L:unless locked
6959: # X:according to user session state
6960: #
6961:
6962: # Possibly locked functionality, check all courses
1.54 www 6963: # Locks might take effect only after 10 minutes cache expiration for other
6964: # courses, and 2 minutes for current course
1.52 www 6965:
6966: my $envkey;
6967: if ($thisallowed=~/L/) {
1.1000 raeburn 6968: foreach $envkey (keys(%env)) {
1.54 www 6969: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6970: my $courseid=$2;
6971: my $roleid=$1.'.'.$2;
1.92 www 6972: $courseid=~s/^\///;
1.54 www 6973: my $expiretime=600;
1.620 albertel 6974: if ($env{'request.role'} eq $roleid) {
1.54 www 6975: $expiretime=120;
6976: }
6977: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6978: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6979: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6980: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6981: }
1.620 albertel 6982: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6983: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6984: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6985: &log($env{'user.domain'},$env{'user.name'},
6986: $env{'user.home'},
1.57 www 6987: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6988: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6989: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6990: return '';
6991: }
6992: }
1.620 albertel 6993: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6994: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6995: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6996: &log($env{'user.domain'},$env{'user.name'},
6997: $env{'user.home'},
1.57 www 6998: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6999: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7000: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7001: return '';
7002: }
7003: }
7004: }
1.29 www 7005: }
1.52 www 7006: }
7007:
7008: #
7009: # Rest of the restrictions depend on selected course
7010: #
7011:
1.620 albertel 7012: unless ($env{'request.course.id'}) {
1.766 albertel 7013: if ($thisallowed eq 'A') {
7014: return 'A';
1.814 raeburn 7015: } elsif ($thisallowed eq 'B') {
7016: return 'B';
1.766 albertel 7017: } else {
7018: return '1';
7019: }
1.52 www 7020: }
1.29 www 7021:
1.52 www 7022: #
7023: # Now user is definitely in a course
7024: #
1.53 www 7025:
7026:
7027: # Course preferences
7028:
7029: if ($thisallowed=~/C/) {
1.620 albertel 7030: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7031: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7032: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7033: =~/\Q$rolecode\E/) {
1.1103 raeburn 7034: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7035: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7036: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7037: $env{'request.course.id'});
7038: }
1.237 www 7039: return '';
7040: }
7041:
1.620 albertel 7042: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7043: =~/\Q$unamedom\E/) {
1.1103 raeburn 7044: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7045: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7046: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7047: $env{'request.course.id'});
7048: }
1.54 www 7049: return '';
7050: }
1.53 www 7051: }
7052:
7053: # Resource preferences
7054:
7055: if ($thisallowed=~/R/) {
1.620 albertel 7056: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7057: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7058: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7059: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7060: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7061: }
7062: return '';
1.54 www 7063: }
1.53 www 7064: }
1.30 www 7065:
1.246 www 7066: # Restricted by state or randomout?
1.30 www 7067:
1.52 www 7068: if ($thisallowed=~/X/) {
1.620 albertel 7069: if ($env{'acc.randomout'}) {
1.579 albertel 7070: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7071: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7072: return '';
7073: }
1.247 www 7074: }
7075: if (&condval($statecond)) {
1.52 www 7076: return '2';
7077: } else {
7078: return '';
7079: }
7080: }
1.30 www 7081:
1.766 albertel 7082: if ($thisallowed eq 'A') {
7083: return 'A';
1.814 raeburn 7084: } elsif ($thisallowed eq 'B') {
7085: return 'B';
1.766 albertel 7086: }
1.52 www 7087: return 'F';
1.232 www 7088: }
1.1162 raeburn 7089:
1.1172.2.13 raeburn 7090: # ------------------------------------------- Check construction space access
7091:
7092: sub constructaccess {
7093: my ($url,$setpriv)=@_;
7094:
7095: # We do not allow editing of previous versions of files
7096: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7097:
7098: # Get username and domain from URL
7099: my ($ownername,$ownerdomain,$ownerhome);
7100:
7101: ($ownerdomain,$ownername) =
7102: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7103:
7104: # The URL does not really point to any authorspace, forget it
7105: unless (($ownername) && ($ownerdomain)) { return ''; }
7106:
7107: # Now we need to see if the user has access to the authorspace of
7108: # $ownername at $ownerdomain
7109:
7110: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7111: # Real author for this?
7112: $ownerhome = $env{'user.home'};
7113: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7114: return ($ownername,$ownerdomain,$ownerhome);
7115: }
7116: } else {
7117: # Co-author for this?
7118: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7119: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7120: $ownerhome = &homeserver($ownername,$ownerdomain);
7121: return ($ownername,$ownerdomain,$ownerhome);
7122: }
7123: }
7124:
7125: # We don't have any access right now. If we are not possibly going to do anything about this,
7126: # we might as well leave
7127: unless ($setpriv) { return ''; }
7128:
7129: # Backdoor access?
7130: my $allowed=&allowed('eco',$ownerdomain);
7131: # Nope
7132: unless ($allowed) { return ''; }
7133: # Looks like we may have access, but could be locked by the owner of the construction space
7134: if ($allowed eq 'U') {
7135: my %blocked=&get('environment',['domcoord.author'],
7136: $ownerdomain,$ownername);
7137: # Is blocked by owner
7138: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7139: }
7140: if (($allowed eq 'F') || ($allowed eq 'U')) {
7141: # Grant temporary access
7142: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7143: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7144: if (!$update) { $update = $then; }
7145: my $refresh=$env{'user.refresh.time'};
7146: if (!$refresh) { $refresh = $update; }
7147: my $now = time;
7148: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7149: $now,'ca','constructaccess');
7150: $ownerhome = &homeserver($ownername,$ownerdomain);
7151: return($ownername,$ownerdomain,$ownerhome);
7152: }
7153: # No business here
7154: return '';
7155: }
7156:
1.1162 raeburn 7157: sub get_comm_blocks {
7158: my ($cdom,$cnum) = @_;
7159: if ($cdom eq '' || $cnum eq '') {
7160: return unless ($env{'request.course.id'});
7161: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7162: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7163: }
7164: my %commblocks;
7165: my $hashid=$cdom.'_'.$cnum;
7166: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7167: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7168: %commblocks = %{$blocksref};
7169: } else {
7170: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7171: my $cachetime = 600;
7172: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7173: }
7174: return %commblocks;
7175: }
7176:
7177: sub has_comm_blocking {
7178: my ($priv,$symb,$uri,$blocks) = @_;
7179: return unless ($env{'request.course.id'});
7180: return unless ($priv eq 'bre');
7181: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7182: my %commblocks;
7183: if (ref($blocks) eq 'HASH') {
7184: %commblocks = %{$blocks};
7185: } else {
7186: %commblocks = &get_comm_blocks();
7187: }
7188: return unless (keys(%commblocks) > 0);
7189: if (!$symb) { $symb=&symbread($uri,1); }
7190: my ($map,$resid,undef)=&decode_symb($symb);
7191: my %tocheck = (
7192: maps => $map,
7193: resources => $symb,
7194: );
7195: my @blockers;
7196: my $now = time;
1.1163 raeburn 7197: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7198: foreach my $block (keys(%commblocks)) {
7199: if ($block =~ /^(\d+)____(\d+)$/) {
7200: my ($start,$end) = ($1,$2);
7201: if ($start <= $now && $end >= $now) {
7202: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7203: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7204: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7205: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7206: unless (grep(/^\Q$block\E$/,@blockers)) {
7207: push(@blockers,$block);
7208: }
7209: }
7210: }
7211: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7212: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7213: unless (grep(/^\Q$block\E$/,@blockers)) {
7214: push(@blockers,$block);
7215: }
7216: }
7217: }
7218: }
7219: }
7220: }
7221: } elsif ($block =~ /^firstaccess____(.+)$/) {
7222: my $item = $1;
1.1163 raeburn 7223: my @to_test;
1.1162 raeburn 7224: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7225: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7226: my $check_interval;
7227: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7228: my @interval;
7229: my $type = 'map';
7230: if ($item eq 'course') {
7231: $type = 'course';
7232: @interval=&EXT("resource.0.interval");
7233: } else {
7234: if ($item =~ /___\d+___/) {
7235: $type = 'resource';
7236: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7237: if (ref($navmap)) {
7238: my $res = $navmap->getBySymb($item);
7239: push(@to_test,$res);
7240: }
1.1162 raeburn 7241: } else {
7242: my $mapsymb = &symbread($item,1);
7243: if ($mapsymb) {
7244: if (ref($navmap)) {
7245: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7246: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7247: foreach my $res (@to_test) {
1.1162 raeburn 7248: my $symb = $res->symb();
7249: next if ($symb eq $mapsymb);
7250: if ($symb ne '') {
7251: @interval=&EXT("resource.0.interval",$symb);
7252: last;
7253: }
7254: }
7255: }
7256: }
7257: }
7258: }
7259: if ($interval[0] =~ /\d+/) {
7260: my $first_access;
7261: if ($type eq 'resource') {
7262: $first_access=&get_first_access($interval[1],$item);
7263: } elsif ($type eq 'map') {
7264: $first_access=&get_first_access($interval[1],undef,$item);
7265: } else {
7266: $first_access=&get_first_access($interval[1]);
7267: }
7268: if ($first_access) {
7269: my $timesup = $first_access+$interval[0];
7270: if ($timesup > $now) {
1.1163 raeburn 7271: foreach my $res (@to_test) {
7272: if ($res->is_problem()) {
7273: if ($res->completable()) {
7274: unless (grep(/^\Q$block\E$/,@blockers)) {
7275: push(@blockers,$block);
7276: }
7277: last;
7278: }
7279: }
1.1162 raeburn 7280: }
7281: }
7282: }
7283: }
7284: }
7285: }
7286: }
7287: }
7288: }
7289: return @blockers;
7290: }
7291:
7292: sub check_docs_block {
7293: my ($docsblock,$tocheck) =@_;
7294: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7295: return;
7296: }
7297: if (ref($docsblock->{'maps'}) eq 'HASH') {
7298: if ($tocheck->{'maps'}) {
7299: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7300: return 1;
7301: }
7302: }
7303: }
7304: if (ref($docsblock->{'resources'}) eq 'HASH') {
7305: if ($tocheck->{'resources'}) {
7306: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7307: return 1;
7308: }
7309: }
7310: }
7311: return;
7312: }
7313:
1.1133 foxr 7314: #
7315: # Removes the versino from a URI and
7316: # splits it in to its filename and path to the filename.
7317: # Seems like File::Basename could have done this more clearly.
7318: # Parameters:
7319: # $uri - input URI
7320: # Returns:
7321: # Two element list consisting of
7322: # $pathname - the URI up to and excluding the trailing /
7323: # $filename - The part of the URI following the last /
7324: # NOTE:
7325: # Another realization of this is simply:
7326: # use File::Basename;
7327: # ...
7328: # $uri = shift;
7329: # $filename = basename($uri);
7330: # $path = dirname($uri);
7331: # return ($filename, $path);
7332: #
7333: # The implementation below is probably faster however.
7334: #
1.710 albertel 7335: sub split_uri_for_cond {
7336: my $uri=&deversion(&declutter(shift));
7337: my @uriparts=split(/\//,$uri);
7338: my $filename=pop(@uriparts);
7339: my $pathname=join('/',@uriparts);
7340: return ($pathname,$filename);
7341: }
1.232 www 7342: # --------------------------------------------------- Is a resource on the map?
7343:
7344: sub is_on_map {
1.710 albertel 7345: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7346: #Trying to find the conditional for the file
1.620 albertel 7347: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7348: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7349: if ($match) {
1.289 bowersj2 7350: return (1,$1);
7351: } else {
1.434 www 7352: return (0,0);
1.289 bowersj2 7353: }
1.12 www 7354: }
7355:
1.427 www 7356: # --------------------------------------------------------- Get symb from alias
7357:
7358: sub get_symb_from_alias {
7359: my $symb=shift;
7360: my ($map,$resid,$url)=&decode_symb($symb);
7361: # Already is a symb
7362: if ($url) { return $symb; }
7363: # Must be an alias
7364: my $aliassymb='';
7365: my %bighash;
1.620 albertel 7366: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7367: &GDBM_READER(),0640)) {
7368: my $rid=$bighash{'mapalias_'.$symb};
7369: if ($rid) {
7370: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7371: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7372: $resid,$bighash{'src_'.$rid});
1.427 www 7373: }
7374: untie %bighash;
7375: }
7376: return $aliassymb;
7377: }
7378:
1.12 www 7379: # ----------------------------------------------------------------- Define Role
7380:
7381: sub definerole {
7382: if (allowed('mcr','/')) {
7383: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7384: foreach my $role (split(':',$sysrole)) {
7385: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7386: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7387: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7388: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7389: return "refused:s:$crole&$cqual";
7390: }
7391: }
1.191 harris41 7392: }
1.800 albertel 7393: foreach my $role (split(':',$domrole)) {
7394: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7395: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7396: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7397: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7398: return "refused:d:$crole&$cqual";
7399: }
7400: }
1.191 harris41 7401: }
1.800 albertel 7402: foreach my $role (split(':',$courole)) {
7403: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7404: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7405: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7406: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7407: return "refused:c:$crole&$cqual";
7408: }
7409: }
1.191 harris41 7410: }
1.620 albertel 7411: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7412: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7413: "rolesdef_$rolename=".
7414: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7415: return reply($command,$env{'user.home'});
1.12 www 7416: } else {
7417: return 'refused';
7418: }
1.105 harris41 7419: }
7420:
7421: # ---------------- Make a metadata query against the network of library servers
7422:
7423: sub metadata_query {
1.1172.2.33 raeburn 7424: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7425: my %rhash;
1.845 albertel 7426: my %libserv = &all_library();
1.244 matthew 7427: my @server_list = (defined($server_array) ? @$server_array
7428: : keys(%libserv) );
7429: for my $server (@server_list) {
1.1172.2.33 raeburn 7430: my $domains = '';
7431: if (ref($domains_hash) eq 'HASH') {
7432: $domains = $domains_hash->{$server};
7433: }
1.118 harris41 7434: unless ($custom or $customshow) {
1.1172.2.33 raeburn 7435: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7436: $rhash{$server}=$reply;
7437: }
7438: else {
7439: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 7440: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7441: $server);
7442: $rhash{$server}=$reply;
7443: }
1.112 harris41 7444: }
1.118 harris41 7445: return \%rhash;
1.240 www 7446: }
7447:
7448: # ----------------------------------------- Send log queries and wait for reply
7449:
7450: sub log_query {
7451: my ($uname,$udom,$query,%filters)=@_;
7452: my $uhome=&homeserver($uname,$udom);
7453: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7454: my $uhost=&hostname($uhome);
1.800 albertel 7455: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7456: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7457: $uhome);
1.479 albertel 7458: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7459: return get_query_reply($queryid);
7460: }
7461:
1.818 raeburn 7462: # -------------------------- Update MySQL table for portfolio file
7463:
7464: sub update_portfolio_table {
1.821 raeburn 7465: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7466: if ($group ne '') {
7467: $file_name =~s /^\Q$group\E//;
7468: }
1.818 raeburn 7469: my $homeserver = &homeserver($uname,$udom);
7470: my $queryid=
1.821 raeburn 7471: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7472: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7473: my $reply = &get_query_reply($queryid);
7474: return $reply;
7475: }
7476:
1.899 raeburn 7477: # -------------------------- Update MySQL allusers table
7478:
7479: sub update_allusers_table {
7480: my ($uname,$udom,$names) = @_;
7481: my $homeserver = &homeserver($uname,$udom);
7482: my $queryid=
7483: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7484: 'lastname='.&escape($names->{'lastname'}).'%%'.
7485: 'firstname='.&escape($names->{'firstname'}).'%%'.
7486: 'middlename='.&escape($names->{'middlename'}).'%%'.
7487: 'generation='.&escape($names->{'generation'}).'%%'.
7488: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7489: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7490: return;
1.899 raeburn 7491: }
7492:
1.508 raeburn 7493: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7494:
7495: sub fetch_enrollment_query {
1.511 raeburn 7496: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7497: my $homeserver;
1.547 raeburn 7498: my $maxtries = 1;
1.508 raeburn 7499: if ($context eq 'automated') {
7500: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7501: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7502: } else {
7503: $homeserver = &homeserver($cnum,$dom);
7504: }
1.838 albertel 7505: my $host=&hostname($homeserver);
1.506 raeburn 7506: my $cmd = '';
1.1000 raeburn 7507: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7508: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7509: }
7510: $cmd =~ s/%%$//;
7511: $cmd = &escape($cmd);
7512: my $query = 'fetchenrollment';
1.620 albertel 7513: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7514: unless ($queryid=~/^\Q$host\E\_/) {
7515: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7516: return 'error: '.$queryid;
7517: }
1.506 raeburn 7518: my $reply = &get_query_reply($queryid);
1.547 raeburn 7519: my $tries = 1;
7520: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7521: $reply = &get_query_reply($queryid);
7522: $tries ++;
7523: }
1.526 raeburn 7524: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7525: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7526: } else {
1.901 albertel 7527: my @responses = split(/:/,$reply);
1.515 raeburn 7528: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7529: foreach my $line (@responses) {
7530: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7531: $$replyref{$key} = $value;
7532: }
7533: } else {
1.1117 foxr 7534: my $pathname = LONCAPA::tempdir();
1.800 albertel 7535: foreach my $line (@responses) {
7536: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7537: $$replyref{$key} = $value;
7538: if ($value > 0) {
1.800 albertel 7539: foreach my $item (@{$$affiliatesref{$key}}) {
7540: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7541: my $destname = $pathname.'/'.$filename;
7542: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7543: if ($xml_classlist =~ /^error/) {
7544: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7545: } else {
1.506 raeburn 7546: if ( open(FILE,">$destname") ) {
7547: print FILE &unescape($xml_classlist);
7548: close(FILE);
1.526 raeburn 7549: } else {
7550: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7551: }
7552: }
7553: }
7554: }
7555: }
7556: }
7557: return 'ok';
7558: }
7559: return 'error';
7560: }
7561:
1.242 www 7562: sub get_query_reply {
7563: my $queryid=shift;
1.1117 foxr 7564: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7565: my $reply='';
7566: for (1..100) {
7567: sleep 2;
7568: if (-e $replyfile.'.end') {
1.448 albertel 7569: if (open(my $fh,$replyfile)) {
1.904 albertel 7570: $reply = join('',<$fh>);
7571: close($fh);
1.240 www 7572: } else { return 'error: reply_file_error'; }
1.242 www 7573: return &unescape($reply);
7574: }
1.240 www 7575: }
1.242 www 7576: return 'timeout:'.$queryid;
1.240 www 7577: }
7578:
7579: sub courselog_query {
1.241 www 7580: #
7581: # possible filters:
7582: # url: url or symb
7583: # username
7584: # domain
7585: # action: view, submit, grade
7586: # start: timestamp
7587: # end: timestamp
7588: #
1.240 www 7589: my (%filters)=@_;
1.620 albertel 7590: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7591: if ($filters{'url'}) {
7592: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7593: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7594: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7595: }
1.620 albertel 7596: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7597: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7598: return &log_query($cname,$cdom,'courselog',%filters);
7599: }
7600:
7601: sub userlog_query {
1.858 raeburn 7602: #
7603: # possible filters:
7604: # action: log check role
7605: # start: timestamp
7606: # end: timestamp
7607: #
1.240 www 7608: my ($uname,$udom,%filters)=@_;
7609: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7610: }
7611:
1.506 raeburn 7612: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7613:
7614: sub auto_run {
1.508 raeburn 7615: my ($cnum,$cdom) = @_;
1.876 raeburn 7616: my $response = 0;
7617: my $settings;
7618: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7619: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7620: $settings = $domconfig{'autoenroll'};
7621: if ($settings->{'run'} eq '1') {
7622: $response = 1;
7623: }
7624: } else {
1.934 raeburn 7625: my $homeserver;
7626: if (&is_course($cdom,$cnum)) {
7627: $homeserver = &homeserver($cnum,$cdom);
7628: } else {
7629: $homeserver = &domain($cdom,'primary');
7630: }
7631: if ($homeserver ne 'no_host') {
7632: $response = &reply('autorun:'.$cdom,$homeserver);
7633: }
1.876 raeburn 7634: }
1.506 raeburn 7635: return $response;
7636: }
1.776 albertel 7637:
1.506 raeburn 7638: sub auto_get_sections {
1.508 raeburn 7639: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7640: my $homeserver;
7641: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7642: $homeserver = &homeserver($cnum,$cdom);
7643: }
7644: if (!defined($homeserver)) {
7645: if ($cdom =~ /^$match_domain$/) {
7646: $homeserver = &domain($cdom,'primary');
7647: }
7648: }
7649: my @secs;
7650: if (defined($homeserver)) {
7651: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7652: unless ($response eq 'refused') {
7653: @secs = split(/:/,$response);
7654: }
1.506 raeburn 7655: }
7656: return @secs;
7657: }
1.776 albertel 7658:
1.506 raeburn 7659: sub auto_new_course {
1.1099 raeburn 7660: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7661: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7662: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7663: return $response;
7664: }
1.776 albertel 7665:
1.506 raeburn 7666: sub auto_validate_courseID {
1.508 raeburn 7667: my ($cnum,$cdom,$inst_course_id) = @_;
7668: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7669: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7670: return $response;
7671: }
1.776 albertel 7672:
1.1007 raeburn 7673: sub auto_validate_instcode {
1.1020 raeburn 7674: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7675: my ($homeserver,$response);
7676: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7677: $homeserver = &homeserver($cnum,$cdom);
7678: }
7679: if (!defined($homeserver)) {
7680: if ($cdom =~ /^$match_domain$/) {
7681: $homeserver = &domain($cdom,'primary');
7682: }
7683: }
1.1065 raeburn 7684: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7685: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 7686: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7687: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7688: }
7689:
1.506 raeburn 7690: sub auto_create_password {
1.873 raeburn 7691: my ($cnum,$cdom,$authparam,$udom) = @_;
7692: my ($homeserver,$response);
1.506 raeburn 7693: my $create_passwd = 0;
7694: my $authchk = '';
1.873 raeburn 7695: if ($udom =~ /^$match_domain$/) {
7696: $homeserver = &domain($udom,'primary');
7697: }
7698: if ($homeserver eq '') {
7699: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7700: $homeserver = &homeserver($cnum,$cdom);
7701: }
7702: }
7703: if ($homeserver eq '') {
7704: $authchk = 'nodomain';
1.506 raeburn 7705: } else {
1.873 raeburn 7706: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7707: if ($response eq 'refused') {
7708: $authchk = 'refused';
7709: } else {
1.901 albertel 7710: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7711: }
1.506 raeburn 7712: }
7713: return ($authparam,$create_passwd,$authchk);
7714: }
7715:
1.706 raeburn 7716: sub auto_photo_permission {
7717: my ($cnum,$cdom,$students) = @_;
7718: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7719: my ($outcome,$perm_reqd,$conditions) =
7720: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7721: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7722: return (undef,undef);
7723: }
1.706 raeburn 7724: return ($outcome,$perm_reqd,$conditions);
7725: }
7726:
7727: sub auto_checkphotos {
7728: my ($uname,$udom,$pid) = @_;
7729: my $homeserver = &homeserver($uname,$udom);
7730: my ($result,$resulttype);
7731: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7732: &escape($uname).':'.&escape($pid),
7733: $homeserver));
1.709 albertel 7734: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7735: return (undef,undef);
7736: }
1.706 raeburn 7737: if ($outcome) {
7738: ($result,$resulttype) = split(/:/,$outcome);
7739: }
7740: return ($result,$resulttype);
7741: }
7742:
7743: sub auto_photochoice {
7744: my ($cnum,$cdom) = @_;
7745: my $homeserver = &homeserver($cnum,$cdom);
7746: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7747: &escape($cdom),
7748: $homeserver)));
1.709 albertel 7749: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7750: return (undef,undef);
7751: }
1.706 raeburn 7752: return ($update,$comment);
7753: }
7754:
7755: sub auto_photoupdate {
7756: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7757: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7758: my $host=&hostname($homeserver);
1.706 raeburn 7759: my $cmd = '';
7760: my $maxtries = 1;
1.800 albertel 7761: foreach my $affiliate (keys(%{$affiliatesref})) {
7762: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7763: }
7764: $cmd =~ s/%%$//;
7765: $cmd = &escape($cmd);
7766: my $query = 'institutionalphotos';
7767: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7768: unless ($queryid=~/^\Q$host\E\_/) {
7769: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7770: return 'error: '.$queryid;
7771: }
7772: my $reply = &get_query_reply($queryid);
7773: my $tries = 1;
7774: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7775: $reply = &get_query_reply($queryid);
7776: $tries ++;
7777: }
7778: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7779: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7780: } else {
7781: my @responses = split(/:/,$reply);
7782: my $outcome = shift(@responses);
7783: foreach my $item (@responses) {
7784: my ($key,$value) = split(/=/,$item);
7785: $$photo{$key} = $value;
7786: }
7787: return $outcome;
7788: }
7789: return 'error';
7790: }
7791:
1.521 raeburn 7792: sub auto_instcode_format {
1.793 albertel 7793: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7794: $cat_order) = @_;
1.521 raeburn 7795: my $courses = '';
1.772 raeburn 7796: my @homeservers;
1.521 raeburn 7797: if ($caller eq 'global') {
1.841 albertel 7798: my %servers = &get_servers($codedom,'library');
7799: foreach my $tryserver (keys(%servers)) {
7800: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7801: push(@homeservers,$tryserver);
7802: }
1.584 raeburn 7803: }
1.1022 raeburn 7804: } elsif ($caller eq 'requests') {
7805: if ($codedom =~ /^$match_domain$/) {
7806: my $chome = &domain($codedom,'primary');
7807: unless ($chome eq 'no_host') {
7808: push(@homeservers,$chome);
7809: }
7810: }
1.521 raeburn 7811: } else {
1.772 raeburn 7812: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7813: }
1.793 albertel 7814: foreach my $code (keys(%{$instcodes})) {
7815: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7816: }
7817: chop($courses);
1.772 raeburn 7818: my $ok_response = 0;
7819: my $response;
7820: while (@homeservers > 0 && $ok_response == 0) {
7821: my $server = shift(@homeservers);
7822: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7823: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7824: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7825: split(/:/,$response);
1.772 raeburn 7826: %{$codes} = (%{$codes},&str2hash($codes_str));
7827: push(@{$codetitles},&str2array($codetitles_str));
7828: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7829: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7830: $ok_response = 1;
7831: }
7832: }
7833: if ($ok_response) {
1.521 raeburn 7834: return 'ok';
1.772 raeburn 7835: } else {
7836: return $response;
1.521 raeburn 7837: }
7838: }
7839:
1.792 raeburn 7840: sub auto_instcode_defaults {
7841: my ($domain,$returnhash,$code_order) = @_;
7842: my @homeservers;
1.841 albertel 7843:
7844: my %servers = &get_servers($domain,'library');
7845: foreach my $tryserver (keys(%servers)) {
7846: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7847: push(@homeservers,$tryserver);
7848: }
1.792 raeburn 7849: }
1.841 albertel 7850:
1.792 raeburn 7851: my $response;
1.841 albertel 7852: foreach my $server (@homeservers) {
1.792 raeburn 7853: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7854: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7855:
7856: foreach my $pair (split(/\&/,$response)) {
7857: my ($name,$value)=split(/\=/,$pair);
7858: if ($name eq 'code_order') {
7859: @{$code_order} = split(/\&/,&unescape($value));
7860: } else {
7861: $returnhash->{&unescape($name)}=&unescape($value);
7862: }
7863: }
7864: return 'ok';
1.792 raeburn 7865: }
1.841 albertel 7866:
7867: return $response;
1.1003 raeburn 7868: }
7869:
7870: sub auto_possible_instcodes {
1.1007 raeburn 7871: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7872: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7873: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7874: return;
7875: }
1.1003 raeburn 7876: my (@homeservers,$uhome);
7877: if (defined(&domain($domain,'primary'))) {
7878: $uhome=&domain($domain,'primary');
7879: push(@homeservers,&domain($domain,'primary'));
7880: } else {
7881: my %servers = &get_servers($domain,'library');
7882: foreach my $tryserver (keys(%servers)) {
7883: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7884: push(@homeservers,$tryserver);
7885: }
7886: }
7887: }
7888: my $response;
7889: foreach my $server (@homeservers) {
7890: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7891: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7892: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7893: split(':',$response);
7894: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7895: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7896: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7897: my ($name,$value)=split('=',$item);
7898: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7899: }
7900: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7901: my ($name,$value)=split('=',$item);
7902: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7903: }
7904: return 'ok';
7905: }
7906: return $response;
7907: }
1.792 raeburn 7908:
1.1010 raeburn 7909: sub auto_courserequest_checks {
7910: my ($dom) = @_;
1.1020 raeburn 7911: my ($homeserver,%validations);
7912: if ($dom =~ /^$match_domain$/) {
7913: $homeserver = &domain($dom,'primary');
7914: }
7915: unless ($homeserver eq 'no_host') {
7916: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7917: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7918: my @items = split(/&/,$response);
7919: foreach my $item (@items) {
7920: my ($key,$value) = split('=',$item);
7921: $validations{&unescape($key)} = &thaw_unescape($value);
7922: }
7923: }
7924: }
1.1010 raeburn 7925: return %validations;
7926: }
7927:
1.1020 raeburn 7928: sub auto_courserequest_validation {
1.1172.2.43 raeburn 7929: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 7930: my ($homeserver,$response);
7931: if ($dom =~ /^$match_domain$/) {
7932: $homeserver = &domain($dom,'primary');
7933: }
1.1172.2.43 raeburn 7934: unless ($homeserver eq 'no_host') {
7935: my $customdata;
7936: if (ref($custominfo) eq 'HASH') {
7937: $customdata = &freeze_escape($custominfo);
7938: }
1.1020 raeburn 7939: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7940: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 7941: ':'.&escape($instcode).':'.&escape($instseclist).':'.
7942: $customdata,$homeserver));
1.1020 raeburn 7943: }
7944: return $response;
7945: }
7946:
1.777 albertel 7947: sub auto_validate_class_sec {
1.918 raeburn 7948: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7949: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7950: my $ownerlist;
7951: if (ref($owners) eq 'ARRAY') {
7952: $ownerlist = join(',',@{$owners});
7953: } else {
7954: $ownerlist = $owners;
7955: }
1.773 raeburn 7956: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7957: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7958: return $response;
7959: }
7960:
1.1172.2.38 raeburn 7961: sub auto_crsreq_update {
7962: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
7963: $code,$inbound) = @_;
7964: my ($homeserver,%crsreqresponse);
7965: if ($cdom =~ /^$match_domain$/) {
7966: $homeserver = &domain($cdom,'primary');
7967: }
7968: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
7969: my $info;
7970: if (ref($inbound) eq 'HASH') {
7971: $info = &freeze_escape($inbound);
7972: }
7973: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
7974: ':'.&escape($action).':'.&escape($ownername).':'.
7975: &escape($ownerdomain).':'.&escape($fullname).':'.
7976: &escape($title).':'.&escape($code).':'.$info,$homeserver);
7977: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7978: my @items = split(/&/,$response);
7979: foreach my $item (@items) {
7980: my ($key,$value) = split('=',$item);
7981: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
7982: }
7983: }
7984: }
7985: return \%crsreqresponse;
7986: }
7987:
1.679 raeburn 7988: # ------------------------------------------------------- Course Group routines
7989:
7990: sub get_coursegroups {
1.809 raeburn 7991: my ($cdom,$cnum,$group,$namespace) = @_;
7992: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7993: }
7994:
1.679 raeburn 7995: sub modify_coursegroup {
7996: my ($cdom,$cnum,$groupsettings) = @_;
7997: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7998: }
7999:
1.809 raeburn 8000: sub toggle_coursegroup_status {
8001: my ($cdom,$cnum,$group,$action) = @_;
8002: my ($from_namespace,$to_namespace);
8003: if ($action eq 'delete') {
8004: $from_namespace = 'coursegroups';
8005: $to_namespace = 'deleted_groups';
8006: } else {
8007: $from_namespace = 'deleted_groups';
8008: $to_namespace = 'coursegroups';
8009: }
8010: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8011: if (my $tmp = &error(%curr_group)) {
8012: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8013: return ('read error',$tmp);
8014: } else {
8015: my %savedsettings = %curr_group;
1.809 raeburn 8016: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8017: my $deloutcome;
8018: if ($result eq 'ok') {
1.809 raeburn 8019: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8020: } else {
8021: return ('write error',$result);
8022: }
8023: if ($deloutcome eq 'ok') {
8024: return 'ok';
8025: } else {
8026: return ('delete error',$deloutcome);
8027: }
8028: }
8029: }
8030:
1.679 raeburn 8031: sub modify_group_roles {
1.957 raeburn 8032: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8033: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8034: my $role = 'gr/'.&escape($userprivs);
8035: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8036: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8037: if ($result eq 'ok') {
8038: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8039: }
1.679 raeburn 8040: return $result;
8041: }
8042:
8043: sub modify_coursegroup_membership {
8044: my ($cdom,$cnum,$membership) = @_;
8045: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8046: return $result;
8047: }
8048:
1.682 raeburn 8049: sub get_active_groups {
8050: my ($udom,$uname,$cdom,$cnum) = @_;
8051: my $now = time;
8052: my %groups = ();
8053: foreach my $key (keys(%env)) {
1.811 albertel 8054: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8055: my ($start,$end) = split(/\./,$env{$key});
8056: if (($end!=0) && ($end<$now)) { next; }
8057: if (($start!=0) && ($start>$now)) { next; }
8058: if ($1 eq $cdom && $2 eq $cnum) {
8059: $groups{$3} = $env{$key} ;
8060: }
8061: }
8062: }
8063: return %groups;
8064: }
8065:
1.683 raeburn 8066: sub get_group_membership {
8067: my ($cdom,$cnum,$group) = @_;
8068: return(&dump('groupmembership',$cdom,$cnum,$group));
8069: }
8070:
8071: sub get_users_groups {
8072: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8073: my @usersgroups;
1.683 raeburn 8074: my $cachetime=1800;
8075:
8076: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8077: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8078: if (defined($cached)) {
1.734 albertel 8079: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8080: } else {
8081: $grouplist = '';
1.816 raeburn 8082: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8083: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8084: my $access_end = $env{'course.'.$courseid.
8085: '.default_enrollment_end_date'};
8086: my $now = time;
8087: foreach my $key (keys(%roleshash)) {
8088: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8089: my $group = $1;
8090: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8091: my $start = $2;
8092: my $end = $1;
8093: if ($start == -1) { next; } # deleted from group
8094: if (($start!=0) && ($start>$now)) { next; }
8095: if (($end!=0) && ($end<$now)) {
8096: if ($access_end && $access_end < $now) {
8097: if ($access_end - $end < 86400) {
8098: push(@usersgroups,$group);
1.733 raeburn 8099: }
8100: }
1.817 raeburn 8101: next;
1.733 raeburn 8102: }
1.817 raeburn 8103: push(@usersgroups,$group);
1.683 raeburn 8104: }
8105: }
8106: }
1.817 raeburn 8107: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8108: $grouplist = join(':',@usersgroups);
8109: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8110: }
1.733 raeburn 8111: return @usersgroups;
1.683 raeburn 8112: }
8113:
8114: sub devalidate_getgroups_cache {
8115: my ($udom,$uname,$cdom,$cnum)=@_;
8116: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8117:
1.683 raeburn 8118: my $hashid="$udom:$uname:$courseid";
8119: &devalidate_cache_new('getgroups',$hashid);
8120: }
8121:
1.12 www 8122: # ------------------------------------------------------------------ Plain Text
8123:
8124: sub plaintext {
1.988 raeburn 8125: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8126: if ($short =~ m{^cr/}) {
1.758 albertel 8127: return (split('/',$short))[-1];
8128: }
1.742 raeburn 8129: if (!defined($cid)) {
8130: $cid = $env{'request.course.id'};
8131: }
8132: my %rolenames = (
1.1008 raeburn 8133: Course => 'std',
8134: Community => 'alt1',
1.742 raeburn 8135: );
1.1037 raeburn 8136: if ($cid ne '') {
8137: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8138: unless ($forcedefault) {
8139: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8140: &Apache::lonlocal::mt_escape(\$roletext);
8141: return &Apache::lonlocal::mt($roletext);
8142: }
8143: }
8144: }
8145: if ((defined($type)) && (defined($rolenames{$type})) &&
8146: (defined($rolenames{$type})) &&
8147: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8148: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8149: } elsif ($cid ne '') {
8150: my $crstype = $env{'course.'.$cid.'.type'};
8151: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8152: (defined($prp{$short}{$rolenames{$crstype}}))) {
8153: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8154: }
1.742 raeburn 8155: }
1.1037 raeburn 8156: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8157: }
8158:
8159: # ----------------------------------------------------------------- Assign Role
8160:
8161: sub assignrole {
1.957 raeburn 8162: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8163: $context)=@_;
1.21 www 8164: my $mrole;
8165: if ($role =~ /^cr\//) {
1.393 www 8166: my $cwosec=$url;
1.811 albertel 8167: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8168: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8169: my $refused = 1;
8170: if ($context eq 'requestcourses') {
8171: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8172: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8173: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8174: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8175: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8176: if ($crsenv{'internal.courseowner'} eq
8177: $env{'user.name'}.':'.$env{'user.domain'}) {
8178: $refused = '';
8179: }
8180: }
8181: }
8182: }
8183: }
8184: if ($refused) {
8185: &logthis('Refused custom assignrole: '.
8186: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8187: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8188: return 'refused';
8189: }
1.104 www 8190: }
1.21 www 8191: $mrole='cr';
1.678 raeburn 8192: } elsif ($role =~ /^gr\//) {
8193: my $cwogrp=$url;
1.811 albertel 8194: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8195: unless (&allowed('mdg',$cwogrp)) {
8196: &logthis('Refused group assignrole: '.
8197: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8198: $env{'user.name'}.' at '.$env{'user.domain'});
8199: return 'refused';
8200: }
8201: $mrole='gr';
1.21 www 8202: } else {
1.82 www 8203: my $cwosec=$url;
1.811 albertel 8204: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8205: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8206: my $refused;
8207: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8208: if (!(&allowed('c'.$role,$url))) {
8209: $refused = 1;
8210: }
8211: } else {
8212: $refused = 1;
8213: }
1.947 raeburn 8214: if ($refused) {
1.1045 raeburn 8215: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8216: if (!$selfenroll && $context eq 'course') {
8217: my %crsenv;
8218: if ($role eq 'cc' || $role eq 'co') {
8219: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8220: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8221: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8222: if ($crsenv{'internal.courseowner'} eq
8223: $env{'user.name'}.':'.$env{'user.domain'}) {
8224: $refused = '';
8225: }
8226: }
8227: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8228: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8229: if ($crsenv{'internal.courseowner'} eq
8230: $env{'user.name'}.':'.$env{'user.domain'}) {
8231: $refused = '';
8232: }
8233: }
8234: }
8235: }
8236: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8237: $refused = '';
1.1017 raeburn 8238: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8239: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8240: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8241: my $wrongcc;
8242: if ($cnum =~ /^$match_community$/) {
8243: $wrongcc = 1 if ($role eq 'cc');
8244: } else {
8245: $wrongcc = 1 if ($role eq 'co');
8246: }
8247: unless ($wrongcc) {
8248: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8249: if ($crsenv{'internal.courseowner'} eq
8250: $env{'user.name'}.':'.$env{'user.domain'}) {
8251: $refused = '';
8252: }
1.1017 raeburn 8253: }
8254: }
1.1172.2.9 raeburn 8255: } elsif ($context eq 'requestauthor') {
8256: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8257: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8258: if ($env{'environment.requestauthor'} eq 'automatic') {
8259: $refused = '';
8260: } else {
8261: my %domdefaults = &get_domain_defaults($udom);
8262: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8263: my $checkbystatus;
8264: if ($env{'user.adv'}) {
8265: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8266: if ($disposition eq 'automatic') {
8267: $refused = '';
8268: } elsif ($disposition eq '') {
8269: $checkbystatus = 1;
8270: }
8271: } else {
8272: $checkbystatus = 1;
8273: }
8274: if ($checkbystatus) {
8275: if ($env{'environment.inststatus'}) {
8276: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8277: foreach my $type (@inststatuses) {
8278: if (($type ne '') &&
8279: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8280: $refused = '';
8281: }
8282: }
8283: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8284: $refused = '';
8285: }
8286: }
8287: }
8288: }
8289: }
1.1017 raeburn 8290: }
8291: if ($refused) {
1.947 raeburn 8292: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8293: ' '.$role.' '.$end.' '.$start.' by '.
8294: $env{'user.name'}.' at '.$env{'user.domain'});
8295: return 'refused';
8296: }
1.932 raeburn 8297: }
1.1131 raeburn 8298: } elsif ($role eq 'au') {
8299: if ($url ne '/'.$udom.'/') {
8300: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8301: ' to assign author role for '.$uname.':'.$udom.
8302: ' in domain: '.$url.' refused (wrong domain).');
8303: return 'refused';
8304: }
1.104 www 8305: }
1.21 www 8306: $mrole=$role;
8307: }
1.620 albertel 8308: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8309: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8310: if ($end) { $command.='_'.$end; }
1.21 www 8311: if ($start) {
8312: if ($end) {
1.81 www 8313: $command.='_'.$start;
1.21 www 8314: } else {
1.81 www 8315: $command.='_0_'.$start;
1.21 www 8316: }
8317: }
1.739 raeburn 8318: my $origstart = $start;
8319: my $origend = $end;
1.957 raeburn 8320: my $delflag;
1.357 www 8321: # actually delete
8322: if ($deleteflag) {
1.373 www 8323: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8324: # modify command to delete the role
1.620 albertel 8325: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8326: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8327: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8328: # set start and finish to negative values for userrolelog
8329: $start=-1;
8330: $end=-1;
1.957 raeburn 8331: $delflag = 1;
1.357 www 8332: }
8333: }
8334: # send command
1.349 www 8335: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8336: # log new user role if status is ok
1.349 www 8337: if ($answer eq 'ok') {
1.663 raeburn 8338: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 8339: if (($role eq 'cc') || ($role eq 'in') ||
8340: ($role eq 'ep') || ($role eq 'ad') ||
8341: ($role eq 'ta') || ($role eq 'st') ||
8342: ($role=~/^cr/) || ($role eq 'gr') ||
8343: ($role eq 'co')) {
1.1172.2.13 raeburn 8344: # for course roles, perform group memberships changes triggered by role change.
8345: unless ($role =~ /^gr/) {
8346: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8347: $origstart,$selfenroll,$context);
8348: }
1.1172.2.9 raeburn 8349: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8350: $selfenroll,$context);
8351: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8352: ($role eq 'au') || ($role eq 'dc')) {
8353: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8354: $context);
8355: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8356: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8357: $context);
8358: }
1.1053 raeburn 8359: if ($role eq 'cc') {
8360: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8361: }
1.349 www 8362: }
8363: return $answer;
1.169 harris41 8364: }
8365:
1.1053 raeburn 8366: sub autoupdate_coowners {
8367: my ($url,$end,$start,$uname,$udom) = @_;
8368: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8369: if (($cdom ne '') && ($cnum ne '')) {
8370: my $now = time;
8371: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8372: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8373: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8374: my $instcode = $coursehash{'internal.coursecode'};
8375: if ($instcode ne '') {
1.1056 raeburn 8376: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8377: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8378: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8379: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8380: if ($result eq 'valid') {
8381: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8382: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8383: push(@newcoowners,$coowner);
8384: }
8385: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8386: push(@newcoowners,$uname.':'.$udom);
8387: }
8388: @newcoowners = sort(@newcoowners);
8389: } else {
8390: push(@newcoowners,$uname.':'.$udom);
8391: }
8392: } else {
8393: if ($coursehash{'internal.co-owners'}) {
8394: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8395: unless ($coowner eq $uname.':'.$udom) {
8396: push(@newcoowners,$coowner);
8397: }
8398: }
8399: unless (@newcoowners > 0) {
8400: $delcoowners = 1;
8401: $coowners = '';
8402: }
8403: }
8404: }
8405: if (@newcoowners || $delcoowners) {
8406: &store_coowners($cdom,$cnum,$coursehash{'home'},
8407: $delcoowners,@newcoowners);
8408: }
8409: }
8410: }
8411: }
8412: }
8413: }
8414: }
8415:
8416: sub store_coowners {
8417: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8418: my $cid = $cdom.'_'.$cnum;
8419: my ($coowners,$delresult,$putresult);
8420: if (@newcoowners) {
8421: $coowners = join(',',@newcoowners);
8422: my %coownershash = (
8423: 'internal.co-owners' => $coowners,
8424: );
8425: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8426: if ($putresult eq 'ok') {
8427: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8428: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8429: }
8430: }
8431: }
8432: if ($delcoowners) {
8433: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8434: if ($delresult eq 'ok') {
8435: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8436: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8437: }
8438: }
8439: }
8440: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8441: my %crsinfo =
8442: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8443: if (ref($crsinfo{$cid}) eq 'HASH') {
8444: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8445: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8446: }
8447: }
8448: }
8449:
1.169 harris41 8450: # -------------------------------------------------- Modify user authentication
1.197 www 8451: # Overrides without validation
8452:
1.169 harris41 8453: sub modifyuserauth {
8454: my ($udom,$uname,$umode,$upass)=@_;
8455: my $uhome=&homeserver($uname,$udom);
1.197 www 8456: unless (&allowed('mau',$udom)) { return 'refused'; }
8457: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8458: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8459: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8460: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8461: &escape($upass),$uhome);
1.620 albertel 8462: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8463: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8464: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8465: &log($udom,,$uname,$uhome,
1.620 albertel 8466: 'Authentication changed by '.$env{'user.domain'}.', '.
8467: $env{'user.name'}.', '.$umode.
1.197 www 8468: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8469: unless ($reply eq 'ok') {
1.197 www 8470: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8471: return 'error: '.$reply;
8472: }
1.170 harris41 8473: return 'ok';
1.80 www 8474: }
8475:
1.81 www 8476: # --------------------------------------------------------------- Modify a user
1.80 www 8477:
1.81 www 8478: sub modifyuser {
1.206 matthew 8479: my ($udom, $uname, $uid,
8480: $umode, $upass, $first,
8481: $middle, $last, $gene,
1.1058 raeburn 8482: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8483: $udom= &LONCAPA::clean_domain($udom);
8484: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8485: my $showcandelete = 'none';
8486: if (ref($candelete) eq 'ARRAY') {
8487: if (@{$candelete} > 0) {
8488: $showcandelete = join(', ',@{$candelete});
8489: }
8490: }
1.81 www 8491: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8492: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8493: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8494: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8495: ' desiredhome not specified').
1.620 albertel 8496: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8497: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8498: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8499: my $newuser;
8500: if ($uhome eq 'no_host') {
8501: $newuser = 1;
8502: }
1.80 www 8503: # ----------------------------------------------------------------- Create User
1.406 albertel 8504: if (($uhome eq 'no_host') &&
8505: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8506: my $unhome='';
1.844 albertel 8507: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8508: $unhome = $desiredhome;
1.620 albertel 8509: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8510: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8511: } else { # load balancing routine for determining $unhome
1.81 www 8512: my $loadm=10000000;
1.841 albertel 8513: my %servers = &get_servers($udom,'library');
8514: foreach my $tryserver (keys(%servers)) {
8515: my $answer=reply('load',$tryserver);
8516: if (($answer=~/\d+/) && ($answer<$loadm)) {
8517: $loadm=$answer;
8518: $unhome=$tryserver;
8519: }
1.80 www 8520: }
8521: }
8522: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8523: return 'error: unable to find a home server for '.$uname.
8524: ' in domain '.$udom;
1.80 www 8525: }
8526: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8527: &escape($upass),$unhome);
8528: unless ($reply eq 'ok') {
8529: return 'error: '.$reply;
8530: }
1.230 stredwic 8531: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8532: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8533: return 'error: unable verify users home machine.';
1.80 www 8534: }
1.209 matthew 8535: } # End of creation of new user
1.80 www 8536: # ---------------------------------------------------------------------- Add ID
8537: if ($uid) {
8538: $uid=~tr/A-Z/a-z/;
8539: my %uidhash=&idrget($udom,$uname);
1.196 www 8540: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8541: && (!$forceid)) {
1.80 www 8542: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8543: return 'error: user id "'.$uid.'" does not match '.
8544: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8545: }
8546: } else {
8547: &idput($udom,($uname => $uid));
8548: }
8549: }
8550: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8551: my @tmp=&get('environment',
1.899 raeburn 8552: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8553: 'permanentemail','inststatus'],
1.134 albertel 8554: $udom,$uname);
1.1075 raeburn 8555: my (%names,%oldnames);
1.313 matthew 8556: if ($tmp[0] =~ m/^error:.*/) {
8557: %names=();
8558: } else {
8559: %names = @tmp;
1.1075 raeburn 8560: %oldnames = %names;
1.313 matthew 8561: }
1.388 www 8562: #
1.1058 raeburn 8563: # If name, email and/or uid are blank (e.g., because an uploaded file
8564: # of users did not contain them), do not overwrite existing values
8565: # unless field is in $candelete array ref.
8566: #
8567:
8568: my @fields = ('firstname','middlename','lastname','generation',
8569: 'permanentemail','id');
8570: my %newvalues;
8571: if (ref($candelete) eq 'ARRAY') {
8572: foreach my $field (@fields) {
8573: if (grep(/^\Q$field\E$/,@{$candelete})) {
8574: if ($field eq 'firstname') {
8575: $names{$field} = $first;
8576: } elsif ($field eq 'middlename') {
8577: $names{$field} = $middle;
8578: } elsif ($field eq 'lastname') {
8579: $names{$field} = $last;
8580: } elsif ($field eq 'generation') {
8581: $names{$field} = $gene;
8582: } elsif ($field eq 'permanentemail') {
8583: $names{$field} = $email;
8584: } elsif ($field eq 'id') {
8585: $names{$field} = $uid;
8586: }
8587: }
8588: }
8589: }
1.388 www 8590: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8591: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8592: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8593: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8594: if ($email) {
8595: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8596: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8597: }
1.899 raeburn 8598: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8599: if (defined($inststatus)) {
8600: $names{'inststatus'} = '';
8601: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8602: if (ref($usertypes) eq 'HASH') {
8603: my @okstatuses;
8604: foreach my $item (split(/:/,$inststatus)) {
8605: if (defined($usertypes->{$item})) {
8606: push(@okstatuses,$item);
8607: }
8608: }
8609: if (@okstatuses) {
8610: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8611: }
8612: }
8613: }
1.1075 raeburn 8614: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8615: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8616: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8617: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8618: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8619: } else {
8620: $logmsg .= ' during self creation';
8621: }
1.1075 raeburn 8622: my $changed;
8623: if ($newuser) {
8624: $changed = 1;
8625: } else {
8626: foreach my $field (@fields) {
8627: if ($names{$field} ne $oldnames{$field}) {
8628: $changed = 1;
8629: last;
8630: }
8631: }
8632: }
8633: unless ($changed) {
8634: $logmsg = 'No changes in user information needed for: '.$logmsg;
8635: &logthis($logmsg);
8636: return 'ok';
8637: }
8638: my $reply = &put('environment', \%names, $udom,$uname);
8639: if ($reply ne 'ok') {
8640: return 'error: '.$reply;
8641: }
1.1087 raeburn 8642: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8643: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8644: }
1.1075 raeburn 8645: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8646: &devalidate_cache_new('namescache',$uname.':'.$udom);
8647: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8648: &logthis($logmsg);
1.134 albertel 8649: return 'ok';
1.80 www 8650: }
8651:
1.81 www 8652: # -------------------------------------------------------------- Modify student
1.80 www 8653:
1.81 www 8654: sub modifystudent {
8655: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8656: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19 raeburn 8657: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8658: if (!$cid) {
1.620 albertel 8659: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8660: return 'not_in_class';
8661: }
1.80 www 8662: }
8663: # --------------------------------------------------------------- Make the user
1.81 www 8664: my $reply=&modifyuser
1.209 matthew 8665: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8666: $desiredhome,$email,$inststatus);
1.80 www 8667: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8668: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 8669: # student's environment
1.297 matthew 8670: $uid = undef if (!$forceid);
1.455 albertel 8671: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 8672: $gene,$usec,$end,$start,$type,$locktype,
8673: $cid,$selfenroll,$context,$credits);
1.297 matthew 8674: return $reply;
8675: }
8676:
8677: sub modify_student_enrollment {
1.1172.2.23 raeburn 8678: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8679: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8680: my ($cdom,$cnum,$chome);
8681: if (!$cid) {
1.620 albertel 8682: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8683: return 'not_in_class';
8684: }
1.620 albertel 8685: $cdom=$env{'course.'.$cid.'.domain'};
8686: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8687: } else {
8688: ($cdom,$cnum)=split(/_/,$cid);
8689: }
1.620 albertel 8690: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8691: if (!$chome) {
1.457 raeburn 8692: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8693: }
1.455 albertel 8694: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8695: # Make sure the user exists
1.81 www 8696: my $uhome=&homeserver($uname,$udom);
8697: if (($uhome eq '') || ($uhome eq 'no_host')) {
8698: return 'error: no such user';
8699: }
1.297 matthew 8700: # Get student data if we were not given enough information
8701: if (!defined($first) || $first eq '' ||
8702: !defined($last) || $last eq '' ||
8703: !defined($uid) || $uid eq '' ||
8704: !defined($middle) || $middle eq '' ||
8705: !defined($gene) || $gene eq '') {
1.294 matthew 8706: # They did not supply us with enough data to enroll the student, so
8707: # we need to pick up more information.
1.297 matthew 8708: my %tmp = &get('environment',
1.294 matthew 8709: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8710: ,$udom,$uname);
8711:
1.800 albertel 8712: #foreach my $key (keys(%tmp)) {
8713: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8714: #}
1.294 matthew 8715: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8716: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8717: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8718: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8719: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8720: }
1.556 albertel 8721: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8722: my $user = "$uname:$udom";
8723: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8724: my $reply=cput('classlist',
1.1148 raeburn 8725: {$user =>
1.1172.2.19 raeburn 8726: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8727: $cdom,$cnum);
1.1148 raeburn 8728: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8729: &devalidate_getsection_cache($udom,$uname,$cid);
8730: } else {
1.81 www 8731: return 'error: '.$reply;
8732: }
1.297 matthew 8733: # Add student role to user
1.83 www 8734: my $uurl='/'.$cid;
1.81 www 8735: $uurl=~s/\_/\//g;
8736: if ($usec) {
8737: $uurl.='/'.$usec;
8738: }
1.1148 raeburn 8739: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8740: $selfenroll,$context);
8741: if ($result ne 'ok') {
8742: if ($old_entry{$user} ne '') {
8743: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8744: } else {
8745: $reply = &del('classlist',[$user],$cdom,$cnum);
8746: }
8747: }
8748: return $result;
1.21 www 8749: }
8750:
1.556 albertel 8751: sub format_name {
8752: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8753: my $name;
8754: if ($first ne 'lastname') {
8755: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8756: } else {
8757: if ($lastname=~/\S/) {
8758: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8759: $name=~s/\s+,/,/;
8760: } else {
8761: $name.= $firstname.' '.$middlename.' '.$generation;
8762: }
8763: }
8764: $name=~s/^\s+//;
8765: $name=~s/\s+$//;
8766: $name=~s/\s+/ /g;
8767: return $name;
8768: }
8769:
1.84 www 8770: # ------------------------------------------------- Write to course preferences
8771:
8772: sub writecoursepref {
8773: my ($courseid,%prefs)=@_;
8774: $courseid=~s/^\///;
8775: $courseid=~s/\_/\//g;
8776: my ($cdomain,$cnum)=split(/\//,$courseid);
8777: my $chome=homeserver($cnum,$cdomain);
8778: if (($chome eq '') || ($chome eq 'no_host')) {
8779: return 'error: no such course';
8780: }
8781: my $cstring='';
1.800 albertel 8782: foreach my $pref (keys(%prefs)) {
8783: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8784: }
1.84 www 8785: $cstring=~s/\&$//;
8786: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8787: }
8788:
8789: # ---------------------------------------------------------- Make/modify course
8790:
8791: sub createcourse {
1.741 raeburn 8792: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8793: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8794: $url=&declutter($url);
8795: my $cid='';
1.1028 raeburn 8796: if ($context eq 'requestcourses') {
8797: my $can_create = 0;
8798: my ($ownername,$ownerdom) = split(':',$course_owner);
8799: if ($udom eq $ownerdom) {
8800: if (&usertools_access($ownername,$ownerdom,$category,undef,
8801: $context)) {
8802: $can_create = 1;
8803: }
8804: } else {
8805: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8806: $category);
8807: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8808: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8809: if (@curr > 0) {
8810: my @options = qw(approval validate autolimit);
8811: my $optregex = join('|',@options);
8812: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8813: $can_create = 1;
8814: }
8815: }
8816: }
8817: }
8818: if ($can_create) {
8819: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8820: unless (&allowed('ccc',$udom)) {
8821: return 'refused';
8822: }
1.1017 raeburn 8823: }
8824: } else {
8825: return 'refused';
8826: }
1.1028 raeburn 8827: } elsif (!&allowed('ccc',$udom)) {
8828: return 'refused';
1.84 www 8829: }
1.1011 raeburn 8830: # --------------------------------------------------------------- Get Unique ID
8831: my $uname;
8832: if ($cnum =~ /^$match_courseid$/) {
8833: my $chome=&homeserver($cnum,$udom,'true');
8834: if (($chome eq '') || ($chome eq 'no_host')) {
8835: $uname = $cnum;
8836: } else {
1.1038 raeburn 8837: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8838: }
8839: } else {
1.1038 raeburn 8840: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8841: }
8842: return $uname if ($uname =~ /^error/);
8843: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8844: if (!defined($course_server)) {
8845: if (defined(&domain($udom,'primary'))) {
8846: $course_server = &domain($udom,'primary');
8847: } else {
8848: $course_server = $env{'user.home'};
8849: }
8850: }
8851: my %host_servers =
8852: &Apache::lonnet::get_servers($udom,'library');
8853: unless ($host_servers{$course_server}) {
8854: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8855: }
1.84 www 8856: # ------------------------------------------------------------- Make the course
8857: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8858: $course_server);
1.84 www 8859: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8860: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8861: if (($uhome eq '') || ($uhome eq 'no_host')) {
8862: return 'error: no such course';
8863: }
1.271 www 8864: # ----------------------------------------------------------------- Course made
1.516 raeburn 8865: # log existence
1.1029 raeburn 8866: my $now = time;
1.918 raeburn 8867: my $newcourse = {
8868: $udom.'_'.$uname => {
1.921 raeburn 8869: description => $description,
8870: inst_code => $inst_code,
8871: owner => $course_owner,
8872: type => $crstype,
1.1029 raeburn 8873: creator => $env{'user.name'}.':'.
8874: $env{'user.domain'},
8875: created => $now,
8876: context => $context,
1.918 raeburn 8877: },
8878: };
1.921 raeburn 8879: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8880: # set toplevel url
1.271 www 8881: my $topurl=$url;
8882: unless ($nonstandard) {
8883: # ------------------------------------------ For standard courses, make top url
8884: my $mapurl=&clutter($url);
1.278 www 8885: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8886: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8887: <map>
8888: <resource id="1" type="start"></resource>
8889: <resource id="2" src="$mapurl"></resource>
8890: <resource id="3" type="finish"></resource>
8891: <link index="1" from="1" to="2"></link>
8892: <link index="2" from="2" to="3"></link>
8893: </map>
8894: ENDINITMAP
8895: $topurl=&declutter(
1.638 albertel 8896: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8897: );
8898: }
8899: # ----------------------------------------------------------- Write preferences
1.84 www 8900: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8901: ('description' => $description,
8902: 'url' => $topurl,
8903: 'internal.creator' => $env{'user.name'}.':'.
8904: $env{'user.domain'},
8905: 'internal.created' => $now,
8906: 'internal.creationcontext' => $context)
8907: );
1.84 www 8908: return '/'.$udom.'/'.$uname;
8909: }
8910:
1.1011 raeburn 8911: # ------------------------------------------------------------------- Create ID
8912: sub generate_coursenum {
1.1038 raeburn 8913: my ($udom,$crstype) = @_;
1.1011 raeburn 8914: my $domdesc = &domain($udom);
8915: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8916: my $first;
8917: if ($crstype eq 'Community') {
8918: $first = '0';
8919: } else {
8920: $first = int(1+rand(9));
8921: }
8922: my $uname=$first.
1.1011 raeburn 8923: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8924: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8925: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8926: # ----------------------------------------------- Make sure that does not exist
8927: my $uhome=&homeserver($uname,$udom,'true');
8928: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8929: if ($crstype eq 'Community') {
8930: $first = '0';
8931: } else {
8932: $first = int(1+rand(9));
8933: }
8934: $uname=$first.
1.1011 raeburn 8935: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8936: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8937: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8938: $uhome=&homeserver($uname,$udom,'true');
8939: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8940: return 'error: unable to generate unique course-ID';
8941: }
8942: }
8943: return $uname;
8944: }
8945:
1.813 albertel 8946: sub is_course {
1.1167 droeschl 8947: my ($cdom, $cnum) = scalar(@_) == 1 ?
8948: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8949:
8950: return unless $cdom and $cnum;
8951:
8952: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8953: '.');
8954:
1.1172.2.23 raeburn 8955: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8956: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8957: }
8958:
1.1015 raeburn 8959: sub store_userdata {
8960: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8961: my $result;
1.1016 raeburn 8962: if ($datakey ne '') {
1.1013 raeburn 8963: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8964: if ($udom eq '' || $uname eq '') {
8965: $udom = $env{'user.domain'};
8966: $uname = $env{'user.name'};
8967: }
8968: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8969: if (($uhome eq '') || ($uhome eq 'no_host')) {
8970: $result = 'error: no_host';
8971: } else {
8972: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8973: $storehash->{'host'} = $perlvar{'lonHostID'};
8974:
8975: my $namevalue='';
8976: foreach my $key (keys(%{$storehash})) {
8977: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8978: }
8979: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 8980: unless ($namespace eq 'courserequests') {
8981: $datakey = &escape($datakey);
8982: }
1.1105 raeburn 8983: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8984: $namevalue,$uhome);
1.1013 raeburn 8985: }
8986: } else {
8987: $result = 'error: data to store was not a hash reference';
8988: }
8989: } else {
8990: $result= 'error: invalid requestkey';
8991: }
8992: return $result;
8993: }
8994:
1.21 www 8995: # ---------------------------------------------------------- Assign Custom Role
8996:
8997: sub assigncustomrole {
1.957 raeburn 8998: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8999: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9000: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9001: }
9002:
9003: # ----------------------------------------------------------------- Revoke Role
9004:
9005: sub revokerole {
1.957 raeburn 9006: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9007: my $now=time;
1.965 raeburn 9008: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9009: }
9010:
9011: # ---------------------------------------------------------- Revoke Custom Role
9012:
9013: sub revokecustomrole {
1.957 raeburn 9014: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9015: my $now=time;
1.357 www 9016: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9017: $deleteflag,$selfenroll,$context);
1.17 www 9018: }
9019:
1.533 banghart 9020: # ------------------------------------------------------------ Disk usage
1.535 albertel 9021: sub diskusage {
1.955 raeburn 9022: my ($udom,$uname,$directorypath,$getpropath)=@_;
9023: $directorypath =~ s/\/$//;
9024: my $listing=&reply('du2:'.&escape($directorypath).':'
9025: .&escape($getpropath).':'.&escape($uname).':'
9026: .&escape($udom),homeserver($uname,$udom));
9027: if ($listing eq 'unknown_cmd') {
9028: if ($getpropath) {
9029: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9030: }
9031: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9032: }
1.514 albertel 9033: return $listing;
1.512 banghart 9034: }
9035:
1.566 banghart 9036: sub is_locked {
1.1096 raeburn 9037: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9038: my @check;
9039: my $is_locked;
1.1093 raeburn 9040: push (@check,$file_name);
1.613 albertel 9041: my %locked = &get('file_permissions',\@check,
1.620 albertel 9042: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9043: my ($tmp)=keys(%locked);
9044: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9045:
1.566 banghart 9046: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9047: $is_locked = 'false';
9048: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9049: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9050: $is_locked = 'true';
1.1096 raeburn 9051: if (ref($which) eq 'ARRAY') {
9052: push(@{$which},$entry);
9053: } else {
9054: last;
9055: }
1.745 raeburn 9056: }
9057: }
1.566 banghart 9058: } else {
9059: $is_locked = 'false';
9060: }
1.1093 raeburn 9061: return $is_locked;
1.566 banghart 9062: }
9063:
1.759 albertel 9064: sub declutter_portfile {
9065: my ($file) = @_;
1.833 albertel 9066: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9067: return $file;
9068: }
9069:
1.559 banghart 9070: # ------------------------------------------------------------- Mark as Read Only
9071:
9072: sub mark_as_readonly {
9073: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9074: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9075: my ($tmp)=keys(%current_permissions);
9076: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9077: foreach my $file (@{$files}) {
1.759 albertel 9078: $file = &declutter_portfile($file);
1.561 banghart 9079: push(@{$current_permissions{$file}},$what);
1.559 banghart 9080: }
1.613 albertel 9081: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9082: return;
9083: }
9084:
1.572 banghart 9085: # ------------------------------------------------------------Save Selected Files
9086:
9087: sub save_selected_files {
9088: my ($user, $path, @files) = @_;
9089: my $filename = $user."savedfiles";
1.573 banghart 9090: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9091: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9092: foreach my $file (@files) {
1.620 albertel 9093: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9094: }
9095: foreach my $file (@other_files) {
1.574 banghart 9096: print (OUT $file."\n");
1.572 banghart 9097: }
1.574 banghart 9098: close (OUT);
1.572 banghart 9099: return 'ok';
9100: }
9101:
1.574 banghart 9102: sub clear_selected_files {
9103: my ($user) = @_;
9104: my $filename = $user."savedfiles";
1.1117 foxr 9105: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9106: print (OUT undef);
9107: close (OUT);
9108: return ("ok");
9109: }
9110:
1.572 banghart 9111: sub files_in_path {
9112: my ($user, $path) = @_;
9113: my $filename = $user."savedfiles";
9114: my %return_files;
1.1117 foxr 9115: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9116: while (my $line_in = <IN>) {
1.574 banghart 9117: chomp ($line_in);
9118: my @paths_and_file = split (m!/!, $line_in);
9119: my $file_part = pop (@paths_and_file);
9120: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9121: $path_part.='/';
9122: my $path_and_file = $path_part.$file_part;
9123: if ($path_part eq $path) {
9124: $return_files{$file_part}= 'selected';
9125: }
9126: }
1.574 banghart 9127: close (IN);
9128: return (\%return_files);
1.572 banghart 9129: }
9130:
9131: # called in portfolio select mode, to show files selected NOT in current directory
9132: sub files_not_in_path {
9133: my ($user, $path) = @_;
9134: my $filename = $user."savedfiles";
9135: my @return_files;
9136: my $path_part;
1.1117 foxr 9137: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9138: while (my $line = <IN>) {
1.572 banghart 9139: #ok, I know it's clunky, but I want it to work
1.800 albertel 9140: my @paths_and_file = split(m|/|, $line);
9141: my $file_part = pop(@paths_and_file);
9142: chomp($file_part);
9143: my $path_part = join('/', @paths_and_file);
1.572 banghart 9144: $path_part .= '/';
9145: my $path_and_file = $path_part.$file_part;
9146: if ($path_part ne $path) {
1.800 albertel 9147: push(@return_files, ($path_and_file));
1.572 banghart 9148: }
9149: }
1.800 albertel 9150: close(OUT);
1.574 banghart 9151: return (@return_files);
1.572 banghart 9152: }
9153:
1.745 raeburn 9154: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9155:
1.745 raeburn 9156: sub get_portfile_permissions {
9157: my ($domain,$user) = @_;
1.613 albertel 9158: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9159: my ($tmp)=keys(%current_permissions);
9160: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9161: return \%current_permissions;
9162: }
9163:
9164: #---------------------------------------------Get portfolio file access controls
9165:
1.749 raeburn 9166: sub get_access_controls {
1.745 raeburn 9167: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9168: my %access;
9169: my $real_file = $file;
9170: $file =~ s/\.meta$//;
1.745 raeburn 9171: if (defined($file)) {
1.749 raeburn 9172: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9173: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9174: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9175: }
9176: }
1.745 raeburn 9177: } else {
1.749 raeburn 9178: foreach my $key (keys(%{$current_permissions})) {
9179: if ($key =~ /\0accesscontrol$/) {
9180: if (defined($group)) {
9181: if ($key !~ m-^\Q$group\E/-) {
9182: next;
9183: }
9184: }
9185: my ($fullpath) = split(/\0/,$key);
9186: if (ref($$current_permissions{$key}) eq 'HASH') {
9187: foreach my $control (keys(%{$$current_permissions{$key}})) {
9188: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9189: }
9190: }
9191: }
9192: }
9193: }
9194: return %access;
9195: }
9196:
9197: sub modify_access_controls {
9198: my ($file_name,$changes,$domain,$user)=@_;
9199: my ($outcome,$deloutcome);
9200: my %store_permissions;
9201: my %new_values;
9202: my %new_control;
9203: my %translation;
9204: my @deletions = ();
9205: my $now = time;
9206: if (exists($$changes{'activate'})) {
9207: if (ref($$changes{'activate'}) eq 'HASH') {
9208: my @newitems = sort(keys(%{$$changes{'activate'}}));
9209: my $numnew = scalar(@newitems);
9210: for (my $i=0; $i<$numnew; $i++) {
9211: my $newkey = $newitems[$i];
9212: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9213: if ($newkey =~ /^\d+:/) {
9214: $newkey =~ s/^(\d+)/$newid/;
9215: $translation{$1} = $newid;
9216: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9217: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9218: $translation{$1} = $newid;
9219: }
1.749 raeburn 9220: $new_values{$file_name."\0".$newkey} =
9221: $$changes{'activate'}{$newitems[$i]};
9222: $new_control{$newkey} = $now;
9223: }
9224: }
9225: }
9226: my %todelete;
9227: my %changed_items;
9228: foreach my $action ('delete','update') {
9229: if (exists($$changes{$action})) {
9230: if (ref($$changes{$action}) eq 'HASH') {
9231: foreach my $key (keys(%{$$changes{$action}})) {
9232: my ($itemnum) = ($key =~ /^([^:]+):/);
9233: if ($action eq 'delete') {
9234: $todelete{$itemnum} = 1;
9235: } else {
9236: $changed_items{$itemnum} = $key;
9237: }
9238: }
1.745 raeburn 9239: }
9240: }
1.749 raeburn 9241: }
9242: # get lock on access controls for file.
9243: my $lockhash = {
9244: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9245: ':'.$env{'user.domain'},
9246: };
9247: my $tries = 0;
9248: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9249:
9250: while (($gotlock ne 'ok') && $tries <3) {
9251: $tries ++;
9252: sleep 1;
9253: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9254: }
9255: if ($gotlock eq 'ok') {
9256: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9257: my ($tmp)=keys(%curr_permissions);
9258: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9259: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9260: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9261: if (ref($curr_controls) eq 'HASH') {
9262: foreach my $control_item (keys(%{$curr_controls})) {
9263: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9264: if (defined($todelete{$itemnum})) {
9265: push(@deletions,$file_name."\0".$control_item);
9266: } else {
9267: if (defined($changed_items{$itemnum})) {
9268: $new_control{$changed_items{$itemnum}} = $now;
9269: push(@deletions,$file_name."\0".$control_item);
9270: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9271: } else {
9272: $new_control{$control_item} = $$curr_controls{$control_item};
9273: }
9274: }
1.745 raeburn 9275: }
9276: }
9277: }
1.970 raeburn 9278: my ($group);
9279: if (&is_course($domain,$user)) {
9280: ($group,my $file) = split(/\//,$file_name,2);
9281: }
1.749 raeburn 9282: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9283: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9284: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9285: # remove lock
9286: my @del_lock = ($file_name."\0".'locked_access_records');
9287: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9288: my $sqlresult =
1.970 raeburn 9289: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9290: $group);
1.749 raeburn 9291: } else {
9292: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9293: }
1.749 raeburn 9294: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9295: }
9296:
1.827 raeburn 9297: sub make_public_indefinitely {
9298: my ($requrl) = @_;
9299: my $now = time;
9300: my $action = 'activate';
9301: my $aclnum = 0;
9302: if (&is_portfolio_url($requrl)) {
9303: my (undef,$udom,$unum,$file_name,$group) =
9304: &parse_portfolio_url($requrl);
9305: my $current_perms = &get_portfile_permissions($udom,$unum);
9306: my %access_controls = &get_access_controls($current_perms,
9307: $group,$file_name);
9308: foreach my $key (keys(%{$access_controls{$file_name}})) {
9309: my ($num,$scope,$end,$start) =
9310: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9311: if ($scope eq 'public') {
9312: if ($start <= $now && $end == 0) {
9313: $action = 'none';
9314: } else {
9315: $action = 'update';
9316: $aclnum = $num;
9317: }
9318: last;
9319: }
9320: }
9321: if ($action eq 'none') {
9322: return 'ok';
9323: } else {
9324: my %changes;
9325: my $newend = 0;
9326: my $newstart = $now;
9327: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9328: $changes{$action}{$newkey} = {
9329: type => 'public',
9330: time => {
9331: start => $newstart,
9332: end => $newend,
9333: },
9334: };
9335: my ($outcome,$deloutcome,$new_values,$translation) =
9336: &modify_access_controls($file_name,\%changes,$udom,$unum);
9337: return $outcome;
9338: }
9339: } else {
9340: return 'invalid';
9341: }
9342: }
9343:
1.745 raeburn 9344: #------------------------------------------------------Get Marked as Read Only
9345:
9346: sub get_marked_as_readonly {
9347: my ($domain,$user,$what,$group) = @_;
9348: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9349: my @readonly_files;
1.629 banghart 9350: my $cmp1=$what;
9351: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9352: while (my ($file_name,$value) = each(%{$current_permissions})) {
9353: if (defined($group)) {
9354: if ($file_name !~ m-^\Q$group\E/-) {
9355: next;
9356: }
9357: }
1.561 banghart 9358: if (ref($value) eq "ARRAY"){
9359: foreach my $stored_what (@{$value}) {
1.629 banghart 9360: my $cmp2=$stored_what;
1.759 albertel 9361: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9362: $cmp2=join('',@{$stored_what});
1.745 raeburn 9363: }
1.629 banghart 9364: if ($cmp1 eq $cmp2) {
1.561 banghart 9365: push(@readonly_files, $file_name);
1.745 raeburn 9366: last;
1.563 banghart 9367: } elsif (!defined($what)) {
9368: push(@readonly_files, $file_name);
1.745 raeburn 9369: last;
1.561 banghart 9370: }
9371: }
1.745 raeburn 9372: }
1.561 banghart 9373: }
9374: return @readonly_files;
9375: }
1.577 banghart 9376: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9377:
1.577 banghart 9378: sub get_marked_as_readonly_hash {
1.745 raeburn 9379: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9380: my %readonly_files;
1.745 raeburn 9381: while (my ($file_name,$value) = each(%{$current_permissions})) {
9382: if (defined($group)) {
9383: if ($file_name !~ m-^\Q$group\E/-) {
9384: next;
9385: }
9386: }
1.577 banghart 9387: if (ref($value) eq "ARRAY"){
9388: foreach my $stored_what (@{$value}) {
1.745 raeburn 9389: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9390: foreach my $lock_descriptor(@{$stored_what}) {
9391: if ($lock_descriptor eq 'graded') {
9392: $readonly_files{$file_name} = 'graded';
9393: } elsif ($lock_descriptor eq 'handback') {
9394: $readonly_files{$file_name} = 'handback';
9395: } else {
9396: if (!exists($readonly_files{$file_name})) {
9397: $readonly_files{$file_name} = 'locked';
9398: }
9399: }
1.745 raeburn 9400: }
1.750 banghart 9401: }
1.577 banghart 9402: }
9403: }
9404: }
9405: return %readonly_files;
9406: }
1.559 banghart 9407: # ------------------------------------------------------------ Unmark as Read Only
9408:
9409: sub unmark_as_readonly {
1.629 banghart 9410: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9411: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9412: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9413: $file_name = &declutter_portfile($file_name);
1.634 albertel 9414: my $symb_crs = $what;
9415: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9416: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9417: my ($tmp)=keys(%current_permissions);
9418: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9419: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9420: foreach my $file (@readonly_files) {
1.759 albertel 9421: my $clean_file = &declutter_portfile($file);
9422: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9423: my $current_locks = $current_permissions{$file};
1.563 banghart 9424: my @new_locks;
9425: my @del_keys;
9426: if (ref($current_locks) eq "ARRAY"){
9427: foreach my $locker (@{$current_locks}) {
1.632 albertel 9428: my $compare=$locker;
1.749 raeburn 9429: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9430: $compare=join('',@{$locker});
1.746 raeburn 9431: if ($compare ne $symb_crs) {
9432: push(@new_locks, $locker);
9433: }
1.563 banghart 9434: }
9435: }
1.650 albertel 9436: if (scalar(@new_locks) > 0) {
1.563 banghart 9437: $current_permissions{$file} = \@new_locks;
9438: } else {
9439: push(@del_keys, $file);
1.613 albertel 9440: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9441: delete($current_permissions{$file});
1.563 banghart 9442: }
9443: }
1.561 banghart 9444: }
1.613 albertel 9445: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9446: return;
9447: }
1.512 banghart 9448:
1.17 www 9449: # ------------------------------------------------------------ Directory lister
9450:
9451: sub dirlist {
1.955 raeburn 9452: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9453: $uri=~s/^\///;
9454: $uri=~s/\/$//;
1.253 stredwic 9455: my ($udom, $uname);
1.955 raeburn 9456: if ($getuserdir) {
1.253 stredwic 9457: $udom = $userdomain;
9458: $uname = $username;
1.955 raeburn 9459: } else {
9460: (undef,$udom,$uname)=split(/\//,$uri);
9461: if(defined($userdomain)) {
9462: $udom = $userdomain;
9463: }
9464: if(defined($username)) {
9465: $uname = $username;
9466: }
1.253 stredwic 9467: }
1.955 raeburn 9468: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9469:
1.955 raeburn 9470: $dirRoot = $perlvar{'lonDocRoot'};
9471: if (defined($getpropath)) {
9472: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9473: $dirRoot =~ s/\/$//;
1.955 raeburn 9474: } elsif (defined($getuserdir)) {
9475: my $subdir=$uname.'__';
9476: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9477: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9478: ."/$udom/$subdir/$uname";
9479: } elsif (defined($alternateRoot)) {
9480: $dirRoot = $alternateRoot;
1.751 banghart 9481: }
1.253 stredwic 9482:
9483: if($udom) {
9484: if($uname) {
1.1135 raeburn 9485: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9486: if ($uhome eq 'no_host') {
9487: return ([],'no_host');
9488: }
1.955 raeburn 9489: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9490: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9491: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9492: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9493: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9494: } else {
9495: @listing_results = map { &unescape($_); } split(/:/,$listing);
9496: }
1.605 matthew 9497: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9498: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9499: @listing_results = split(/:/,$listing);
9500: } else {
9501: @listing_results = map { &unescape($_); } split(/:/,$listing);
9502: }
1.1135 raeburn 9503: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9504: ($listing eq 'rejected') || ($listing eq 'refused') ||
9505: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9506: return ([],$listing);
9507: } else {
9508: return (\@listing_results);
1.1135 raeburn 9509: }
1.955 raeburn 9510: } elsif(!$alternateRoot) {
1.1136 raeburn 9511: my (%allusers,%listerror);
1.841 albertel 9512: my %servers = &get_servers($udom,'library');
1.955 raeburn 9513: foreach my $tryserver (keys(%servers)) {
9514: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9515: &escape($udom),$tryserver);
9516: if ($listing eq 'unknown_cmd') {
9517: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9518: $udom, $tryserver);
9519: } else {
9520: @listing_results = map { &unescape($_); } split(/:/,$listing);
9521: }
1.841 albertel 9522: if ($listing eq 'unknown_cmd') {
9523: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9524: $udom, $tryserver);
9525: @listing_results = split(/:/,$listing);
9526: } else {
9527: @listing_results =
9528: map { &unescape($_); } split(/:/,$listing);
9529: }
1.1136 raeburn 9530: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9531: ($listing eq 'rejected') || ($listing eq 'refused') ||
9532: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9533: $listerror{$tryserver} = $listing;
9534: } else {
1.841 albertel 9535: foreach my $line (@listing_results) {
9536: my ($entry) = split(/&/,$line,2);
9537: $allusers{$entry} = 1;
9538: }
9539: }
1.253 stredwic 9540: }
1.1136 raeburn 9541: my @alluserslist=();
1.800 albertel 9542: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9543: push(@alluserslist,$user.'&user');
1.253 stredwic 9544: }
1.1136 raeburn 9545: return (\@alluserslist);
1.253 stredwic 9546: } else {
1.1136 raeburn 9547: return ([],'missing username');
1.253 stredwic 9548: }
1.955 raeburn 9549: } elsif(!defined($getpropath)) {
1.1136 raeburn 9550: my $path = $perlvar{'lonDocRoot'}.'/res/';
9551: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9552: return (\@all_domains);
1.955 raeburn 9553: } else {
1.1136 raeburn 9554: return ([],'missing domain');
1.275 stredwic 9555: }
9556: }
9557:
9558: # --------------------------------------------- GetFileTimestamp
9559: # This function utilizes dirlist and returns the date stamp for
9560: # when it was last modified. It will also return an error of -1
9561: # if an error occurs
9562:
9563: sub GetFileTimestamp {
1.955 raeburn 9564: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9565: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9566: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9567: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9568: undef,$getuserdir);
9569: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9570: return -1;
9571: }
9572: if (ref($fileref) eq 'ARRAY') {
9573: my @stats = split('&',$fileref->[0]);
1.375 matthew 9574: # @stats contains first the filename, then the stat output
9575: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9576: } else {
9577: return -1;
1.253 stredwic 9578: }
1.26 www 9579: }
9580:
1.712 albertel 9581: sub stat_file {
9582: my ($uri) = @_;
1.787 albertel 9583: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9584:
1.955 raeburn 9585: my ($udom,$uname,$file);
1.712 albertel 9586: if ($uri =~ m-^/(uploaded|editupload)/-) {
9587: ($udom,$uname,$file) =
1.811 albertel 9588: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9589: $file = 'userfiles/'.$file;
9590: }
9591: if ($uri =~ m-^/res/-) {
9592: ($udom,$uname) =
1.807 albertel 9593: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9594: $file = $uri;
9595: }
9596:
9597: if (!$udom || !$uname || !$file) {
9598: # unable to handle the uri
9599: return ();
9600: }
1.956 raeburn 9601: my $getpropath;
9602: if ($file =~ /^userfiles\//) {
9603: $getpropath = 1;
9604: }
1.1136 raeburn 9605: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9606: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9607: return ();
9608: } else {
9609: if (ref($listref) eq 'ARRAY') {
9610: my @stats = split('&',$listref->[0]);
9611: shift(@stats); #filename is first
9612: return @stats;
9613: }
1.712 albertel 9614: }
9615: return ();
9616: }
9617:
1.26 www 9618: # -------------------------------------------------------- Value of a Condition
9619:
1.713 albertel 9620: # gets the value of a specific preevaluated condition
9621: # stored in the string $env{user.state.<cid>}
9622: # or looks up a condition reference in the bighash and if if hasn't
9623: # already been evaluated recurses into docondval to get the value of
9624: # the condition, then memoizing it to
9625: # $env{user.state.<cid>.<condition>}
1.40 www 9626: sub directcondval {
9627: my $number=shift;
1.620 albertel 9628: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9629: &Apache::lonuserstate::evalstate();
9630: }
1.713 albertel 9631: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9632: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9633: } elsif ($number =~ /^_/) {
9634: my $sub_condition;
9635: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9636: &GDBM_READER(),0640)) {
9637: $sub_condition=$bighash{'conditions'.$number};
9638: untie(%bighash);
9639: }
9640: my $value = &docondval($sub_condition);
1.949 raeburn 9641: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9642: return $value;
9643: }
1.620 albertel 9644: if ($env{'user.state.'.$env{'request.course.id'}}) {
9645: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9646: } else {
9647: return 2;
9648: }
9649: }
9650:
1.713 albertel 9651: # get the collection of conditions for this resource
1.26 www 9652: sub condval {
9653: my $condidx=shift;
1.54 www 9654: my $allpathcond='';
1.713 albertel 9655: foreach my $cond (split(/\|/,$condidx)) {
9656: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9657: $allpathcond.=
9658: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9659: }
1.191 harris41 9660: }
1.54 www 9661: $allpathcond=~s/\|$//;
1.713 albertel 9662: return &docondval($allpathcond);
9663: }
9664:
9665: #evaluates an expression of conditions
9666: sub docondval {
9667: my ($allpathcond) = @_;
9668: my $result=0;
9669: if ($env{'request.course.id'}
9670: && defined($allpathcond)) {
9671: my $operand='|';
9672: my @stack;
9673: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9674: if ($chunk eq '(') {
9675: push @stack,($operand,$result);
9676: } elsif ($chunk eq ')') {
9677: my $before=pop @stack;
9678: if (pop @stack eq '&') {
9679: $result=$result>$before?$before:$result;
9680: } else {
9681: $result=$result>$before?$result:$before;
9682: }
9683: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9684: $operand=$chunk;
9685: } else {
9686: my $new=directcondval($chunk);
9687: if ($operand eq '&') {
9688: $result=$result>$new?$new:$result;
9689: } else {
9690: $result=$result>$new?$result:$new;
9691: }
9692: }
9693: }
1.26 www 9694: }
9695: return $result;
1.421 albertel 9696: }
9697:
9698: # ---------------------------------------------------- Devalidate courseresdata
9699:
9700: sub devalidatecourseresdata {
9701: my ($coursenum,$coursedomain)=@_;
9702: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9703: &devalidate_cache_new('courseres',$hashid);
1.28 www 9704: }
9705:
1.763 www 9706:
1.200 www 9707: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9708: #
9709: # Parameters:
9710: # $coursenum - Number of the course.
9711: # $coursedomain - Domain at which the course was created.
9712: # Returns:
9713: # A hash of the course parameters along (I think) with timestamps
9714: # and version info.
1.877 foxr 9715:
1.624 albertel 9716: sub get_courseresdata {
9717: my ($coursenum,$coursedomain)=@_;
1.200 www 9718: my $coursehom=&homeserver($coursenum,$coursedomain);
9719: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9720: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9721: my %dumpreply;
1.417 albertel 9722: unless (defined($cached)) {
1.624 albertel 9723: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9724: $result=\%dumpreply;
1.251 albertel 9725: my ($tmp) = keys(%dumpreply);
9726: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9727: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9728: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9729: return $tmp;
1.416 albertel 9730: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9731: $result=undef;
1.599 albertel 9732: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9733: }
9734: }
1.624 albertel 9735: return $result;
9736: }
9737:
1.633 albertel 9738: sub devalidateuserresdata {
9739: my ($uname,$udom)=@_;
9740: my $hashid="$udom:$uname";
9741: &devalidate_cache_new('userres',$hashid);
9742: }
9743:
1.624 albertel 9744: sub get_userresdata {
9745: my ($uname,$udom)=@_;
9746: #most student don\'t have any data set, check if there is some data
9747: if (&EXT_cache_status($udom,$uname)) { return undef; }
9748:
9749: my $hashid="$udom:$uname";
9750: my ($result,$cached)=&is_cached_new('userres',$hashid);
9751: if (!defined($cached)) {
9752: my %resourcedata=&dump('resourcedata',$udom,$uname);
9753: $result=\%resourcedata;
9754: &do_cache_new('userres',$hashid,$result,600);
9755: }
9756: my ($tmp)=keys(%$result);
9757: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9758: return $result;
9759: }
9760: #error 2 occurs when the .db doesn't exist
9761: if ($tmp!~/error: 2 /) {
1.672 albertel 9762: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9763: " Trying to get resource data for ".
9764: $uname." at ".$udom.": ".
9765: $tmp."</font>");
9766: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9767: #&EXT_cache_set($udom,$uname);
9768: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9769: undef($tmp); # not really an error so don't send it back
1.624 albertel 9770: }
9771: return $tmp;
9772: }
1.879 foxr 9773: #----------------------------------------------- resdata - return resource data
9774: # Purpose:
9775: # Return resource data for either users or for a course.
9776: # Parameters:
9777: # $name - Course/user name.
9778: # $domain - Name of the domain the user/course is registered on.
9779: # $type - Type of thing $name is (must be 'course' or 'user'
9780: # @which - Array of names of resources desired.
9781: # Returns:
9782: # The value of the first reasource in @which that is found in the
9783: # resource hash.
9784: # Exceptional Conditions:
9785: # If the $type passed in is not valid (not the string 'course' or
9786: # 'user', an undefined reference is returned.
9787: # If none of the resources are found, an undef is returned
1.624 albertel 9788: sub resdata {
9789: my ($name,$domain,$type,@which)=@_;
9790: my $result;
9791: if ($type eq 'course') {
9792: $result=&get_courseresdata($name,$domain);
9793: } elsif ($type eq 'user') {
9794: $result=&get_userresdata($name,$domain);
9795: }
9796: if (!ref($result)) { return $result; }
1.251 albertel 9797: foreach my $item (@which) {
1.927 albertel 9798: if (defined($result->{$item->[0]})) {
9799: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9800: }
1.250 albertel 9801: }
1.291 albertel 9802: return undef;
1.200 www 9803: }
9804:
1.1172.2.31 raeburn 9805: sub get_numsuppfiles {
9806: my ($cnum,$cdom,$ignorecache)=@_;
9807: my $hashid=$cnum.':'.$cdom;
9808: my ($suppcount,$cached);
9809: unless ($ignorecache) {
9810: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9811: }
9812: unless (defined($cached)) {
9813: my $chome=&homeserver($cnum,$cdom);
9814: unless ($chome eq 'no_host') {
9815: ($suppcount,my $errors) = (0,0);
9816: my $suppmap = 'supplemental.sequence';
9817: ($suppcount,$errors) =
9818: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9819: }
9820: &do_cache_new('suppcount',$hashid,$suppcount,600);
9821: }
9822: return $suppcount;
9823: }
9824:
1.379 matthew 9825: #
9826: # EXT resource caching routines
9827: #
9828:
9829: sub clear_EXT_cache_status {
1.383 albertel 9830: &delenv('cache.EXT.');
1.379 matthew 9831: }
9832:
9833: sub EXT_cache_status {
9834: my ($target_domain,$target_user) = @_;
1.383 albertel 9835: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9836: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9837: # We know already the user has no data
9838: return 1;
9839: } else {
9840: return 0;
9841: }
9842: }
9843:
9844: sub EXT_cache_set {
9845: my ($target_domain,$target_user) = @_;
1.383 albertel 9846: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9847: #&appenv({$cachename => time});
1.379 matthew 9848: }
9849:
1.28 www 9850: # --------------------------------------------------------- Value of a Variable
1.58 www 9851: sub EXT {
1.715 albertel 9852:
1.1172.2.28 raeburn 9853: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9854: unless ($varname) { return ''; }
1.218 albertel 9855: #get real user name/domain, courseid and symb
9856: my $courseid;
1.359 albertel 9857: my $publicuser;
1.427 www 9858: if ($symbparm) {
9859: $symbparm=&get_symb_from_alias($symbparm);
9860: }
1.218 albertel 9861: if (!($uname && $udom)) {
1.790 albertel 9862: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9863: if (!$symbparm) { $symbparm=$cursymb; }
9864: } else {
1.620 albertel 9865: $courseid=$env{'request.course.id'};
1.218 albertel 9866: }
1.48 www 9867: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9868: my $rest;
1.320 albertel 9869: if (defined($therest[0])) {
1.48 www 9870: $rest=join('.',@therest);
9871: } else {
9872: $rest='';
9873: }
1.320 albertel 9874:
1.57 www 9875: my $qualifierrest=$qualifier;
9876: if ($rest) { $qualifierrest.='.'.$rest; }
9877: my $spacequalifierrest=$space;
9878: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9879: if ($realm eq 'user') {
1.48 www 9880: # --------------------------------------------------------------- user.resource
9881: if ($space eq 'resource') {
1.651 albertel 9882: if ( (defined($Apache::lonhomework::parsing_a_problem)
9883: || defined($Apache::lonhomework::parsing_a_task))
9884: &&
1.744 albertel 9885: ($symbparm eq &symbread()) ) {
9886: # if we are in the middle of processing the resource the
9887: # get the value we are planning on committing
9888: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9889: return $Apache::lonhomework::results{$qualifierrest};
9890: } else {
9891: return $Apache::lonhomework::history{$qualifierrest};
9892: }
1.335 albertel 9893: } else {
1.359 albertel 9894: my %restored;
1.620 albertel 9895: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9896: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9897: } else {
9898: %restored=&restore($symbparm,$courseid,$udom,$uname);
9899: }
1.335 albertel 9900: return $restored{$qualifierrest};
9901: }
1.48 www 9902: # ----------------------------------------------------------------- user.access
9903: } elsif ($space eq 'access') {
1.218 albertel 9904: # FIXME - not supporting calls for a specific user
1.48 www 9905: return &allowed($qualifier,$rest);
9906: # ------------------------------------------ user.preferences, user.environment
9907: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9908: if (($uname eq $env{'user.name'}) &&
9909: ($udom eq $env{'user.domain'})) {
9910: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9911: } else {
1.359 albertel 9912: my %returnhash;
9913: if (!$publicuser) {
9914: %returnhash=&userenvironment($udom,$uname,
9915: $qualifierrest);
9916: }
1.218 albertel 9917: return $returnhash{$qualifierrest};
9918: }
1.48 www 9919: # ----------------------------------------------------------------- user.course
9920: } elsif ($space eq 'course') {
1.218 albertel 9921: # FIXME - not supporting calls for a specific user
1.620 albertel 9922: return $env{join('.',('request.course',$qualifier))};
1.48 www 9923: # ------------------------------------------------------------------- user.role
9924: } elsif ($space eq 'role') {
1.218 albertel 9925: # FIXME - not supporting calls for a specific user
1.620 albertel 9926: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9927: if ($qualifier eq 'value') {
9928: return $role;
9929: } elsif ($qualifier eq 'extent') {
9930: return $where;
9931: }
9932: # ----------------------------------------------------------------- user.domain
9933: } elsif ($space eq 'domain') {
1.218 albertel 9934: return $udom;
1.48 www 9935: # ------------------------------------------------------------------- user.name
9936: } elsif ($space eq 'name') {
1.218 albertel 9937: return $uname;
1.48 www 9938: # ---------------------------------------------------- Any other user namespace
1.29 www 9939: } else {
1.359 albertel 9940: my %reply;
9941: if (!$publicuser) {
9942: %reply=&get($space,[$qualifierrest],$udom,$uname);
9943: }
9944: return $reply{$qualifierrest};
1.48 www 9945: }
1.236 www 9946: } elsif ($realm eq 'query') {
9947: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9948: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9949: [$spacequalifierrest]);
1.620 albertel 9950: return $env{'form.'.$spacequalifierrest};
1.236 www 9951: } elsif ($realm eq 'request') {
1.48 www 9952: # ------------------------------------------------------------- request.browser
9953: if ($space eq 'browser') {
1.1145 bisitz 9954: return $env{'browser.'.$qualifier};
1.57 www 9955: # ------------------------------------------------------------ request.filename
9956: } else {
1.620 albertel 9957: return $env{'request.'.$spacequalifierrest};
1.29 www 9958: }
1.28 www 9959: } elsif ($realm eq 'course') {
1.48 www 9960: # ---------------------------------------------------------- course.description
1.620 albertel 9961: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9962: } elsif ($realm eq 'resource') {
1.165 www 9963:
1.620 albertel 9964: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9965: if (!$symbparm) { $symbparm=&symbread(); }
9966: }
1.693 albertel 9967:
1.1172.2.30 raeburn 9968: if ($qualifier eq '') {
9969: if ($space eq 'title') {
9970: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9971: return &gettitle($symbparm);
9972: }
1.693 albertel 9973:
1.1172.2.30 raeburn 9974: if ($space eq 'map') {
9975: my ($map) = &decode_symb($symbparm);
9976: return &symbread($map);
9977: }
9978: if ($space eq 'maptitle') {
9979: my ($map) = &decode_symb($symbparm);
9980: return &gettitle($map);
9981: }
9982: if ($space eq 'filename') {
9983: if ($symbparm) {
9984: return &clutter((&decode_symb($symbparm))[2]);
9985: }
9986: return &hreflocation('',$env{'request.filename'});
1.905 albertel 9987: }
1.1172.2.30 raeburn 9988:
9989: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
9990: if ($space eq 'visibleparts') {
9991: my $navmap = Apache::lonnavmaps::navmap->new();
9992: my $item;
9993: if (ref($navmap)) {
9994: my $res = $navmap->getBySymb($symbparm);
9995: my $parts = $res->parts();
9996: if (ref($parts) eq 'ARRAY') {
9997: $item = join(',',@{$parts});
9998: }
9999: undef($navmap);
10000: }
10001: return $item;
10002: }
10003: }
10004: }
1.693 albertel 10005:
10006: my ($section, $group, @groups);
1.593 albertel 10007: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 10008: if (($courseid eq '') && ($cid)) {
10009: $courseid = $cid;
10010: }
10011: if (($symbparm && $courseid) &&
10012: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10013:
1.218 albertel 10014: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10015:
1.60 www 10016: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10017: my $symbp=$symbparm;
1.735 albertel 10018: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10019:
10020: my $symbparm=$symbp.'.'.$spacequalifierrest;
10021: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10022:
1.620 albertel 10023: if (($env{'user.name'} eq $uname) &&
10024: ($env{'user.domain'} eq $udom)) {
10025: $section=$env{'request.course.sec'};
1.733 raeburn 10026: @groups = split(/:/,$env{'request.course.groups'});
10027: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10028: } else {
1.539 albertel 10029: if (! defined($usection)) {
1.551 albertel 10030: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10031: } else {
10032: $section = $usection;
10033: }
1.733 raeburn 10034: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10035: }
10036:
10037: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10038: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10039: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10040:
1.593 albertel 10041: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10042: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10043: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10044:
1.60 www 10045: # ----------------------------------------------------------- first, check user
1.624 albertel 10046:
10047: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10048: ([$courselevelr,'resource'],
10049: [$courselevelm,'map' ],
10050: [$courselevel, 'course' ]));
1.931 albertel 10051: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10052:
1.594 albertel 10053: # ------------------------------------------------ second, check some of course
1.684 raeburn 10054: my $coursereply;
1.691 raeburn 10055: if (@groups > 0) {
10056: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10057: $mapparm,$spacequalifierrest);
1.927 albertel 10058: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10059: }
1.96 www 10060:
1.684 raeburn 10061: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10062: $env{'course.'.$courseid.'.domain'},
10063: 'course',
10064: ([$seclevelr, 'resource'],
10065: [$seclevelm, 'map' ],
10066: [$seclevel, 'course' ],
10067: [$courselevelr,'resource']));
10068: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10069:
1.60 www 10070: # ------------------------------------------------------ third, check map parms
1.218 albertel 10071: my %parmhash=();
10072: my $thisparm='';
10073: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10074: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10075: &GDBM_READER(),0640)) {
1.218 albertel 10076: $thisparm=$parmhash{$symbparm};
10077: untie(%parmhash);
10078: }
1.927 albertel 10079: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10080: }
1.594 albertel 10081: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10082:
1.218 albertel 10083: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10084: my $filename;
10085: if (!$symbparm) { $symbparm=&symbread(); }
10086: if ($symbparm) {
1.409 www 10087: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10088: } else {
1.620 albertel 10089: $filename=$env{'request.filename'};
1.282 albertel 10090: }
10091: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10092: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10093: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10094: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10095:
1.927 albertel 10096: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10097: if ($symbparm && defined($courseid) &&
1.620 albertel 10098: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10099: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10100: $env{'course.'.$courseid.'.domain'},
10101: 'course',
1.927 albertel 10102: ([$courselevelm,'map' ],
10103: [$courselevel, 'course']));
10104: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10105: }
1.145 www 10106: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10107: unless ($space eq '0') {
1.336 albertel 10108: my @parts=split(/_/,$space);
10109: my $id=pop(@parts);
10110: my $part=join('_',@parts);
10111: if ($part eq '') { $part='0'; }
1.927 albertel 10112: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10113: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10114: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10115: }
1.395 albertel 10116: if ($recurse) { return undef; }
10117: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10118: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10119: # ---------------------------------------------------- Any other user namespace
10120: } elsif ($realm eq 'environment') {
10121: # ----------------------------------------------------------------- environment
1.620 albertel 10122: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10123: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10124: } else {
1.770 albertel 10125: if ($uname eq 'anonymous' && $udom eq '') {
10126: return '';
10127: }
1.219 albertel 10128: my %returnhash=&userenvironment($udom,$uname,
10129: $spacequalifierrest);
10130: return $returnhash{$spacequalifierrest};
10131: }
1.28 www 10132: } elsif ($realm eq 'system') {
1.48 www 10133: # ----------------------------------------------------------------- system.time
10134: if ($space eq 'time') {
10135: return time;
10136: }
1.696 albertel 10137: } elsif ($realm eq 'server') {
10138: # ----------------------------------------------------------------- system.time
10139: if ($space eq 'name') {
10140: return $ENV{'SERVER_NAME'};
10141: }
1.28 www 10142: }
1.48 www 10143: return '';
1.61 www 10144: }
10145:
1.927 albertel 10146: sub get_reply {
10147: my ($reply_value) = @_;
1.940 raeburn 10148: if (ref($reply_value) eq 'ARRAY') {
10149: if (wantarray) {
10150: return @$reply_value;
10151: }
10152: return $reply_value->[0];
10153: } else {
10154: return $reply_value;
1.927 albertel 10155: }
10156: }
10157:
1.691 raeburn 10158: sub check_group_parms {
10159: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10160: my @groupitems = ();
10161: my $resultitem;
1.927 albertel 10162: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10163: foreach my $group (@{$groups}) {
10164: foreach my $level (@levels) {
1.927 albertel 10165: my $item = $courseid.'.['.$group.'].'.$level->[0];
10166: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10167: }
10168: }
10169: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10170: $env{'course.'.$courseid.'.domain'},
10171: 'course',@groupitems);
10172: return $coursereply;
10173: }
10174:
10175: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10176: my ($courseid,@groups) = @_;
10177: @groups = sort(@groups);
1.691 raeburn 10178: return @groups;
10179: }
10180:
1.395 albertel 10181: sub packages_tab_default {
10182: my ($uri,$varname)=@_;
10183: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10184:
10185: my (@extension,@specifics,$do_default);
10186: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10187: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10188: if ($pack_type eq 'default') {
10189: $do_default=1;
10190: } elsif ($pack_type eq 'extension') {
10191: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10192: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10193: # only look at packages defaults for packages that this id is
1.738 albertel 10194: push(@specifics,[$package,$pack_type,$pack_part]);
10195: }
10196: }
10197: # first look for a package that matches the requested part id
10198: foreach my $package (@specifics) {
10199: my (undef,$pack_type,$pack_part)=@{$package};
10200: next if ($pack_part ne $part);
10201: if (defined($packagetab{"$pack_type&$name&default"})) {
10202: return $packagetab{"$pack_type&$name&default"};
10203: }
10204: }
10205: # look for any possible matching non extension_ package
10206: foreach my $package (@specifics) {
10207: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10208: if (defined($packagetab{"$pack_type&$name&default"})) {
10209: return $packagetab{"$pack_type&$name&default"};
10210: }
1.585 albertel 10211: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10212: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10213: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10214: }
10215: }
1.738 albertel 10216: # look for any posible extension_ match
10217: foreach my $package (@extension) {
10218: my ($package,$pack_type)=@{$package};
10219: if (defined($packagetab{"$pack_type&$name&default"})) {
10220: return $packagetab{"$pack_type&$name&default"};
10221: }
10222: if (defined($packagetab{$package."&$name&default"})) {
10223: return $packagetab{$package."&$name&default"};
10224: }
10225: }
10226: # look for a global default setting
10227: if ($do_default && defined($packagetab{"default&$name&default"})) {
10228: return $packagetab{"default&$name&default"};
10229: }
1.395 albertel 10230: return undef;
10231: }
10232:
1.334 albertel 10233: sub add_prefix_and_part {
10234: my ($prefix,$part)=@_;
10235: my $keyroot;
10236: if (defined($prefix) && $prefix !~ /^__/) {
10237: # prefix that has a part already
10238: $keyroot=$prefix;
10239: } elsif (defined($prefix)) {
10240: # prefix that is missing a part
10241: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10242: } else {
10243: # no prefix at all
10244: if (defined($part)) { $keyroot='_'.$part; }
10245: }
10246: return $keyroot;
10247: }
10248:
1.71 www 10249: # ---------------------------------------------------------------- Get metadata
10250:
1.599 albertel 10251: my %metaentry;
1.1070 www 10252: my %importedpartids;
1.71 www 10253: sub metadata {
1.176 www 10254: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10255: $uri=&declutter($uri);
1.288 albertel 10256: # if it is a non metadata possible uri return quickly
1.529 albertel 10257: if (($uri eq '') ||
10258: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 10259: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10260: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10261: return undef;
10262: }
1.1140 www 10263: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 10264: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10265: return undef;
1.288 albertel 10266: }
1.73 www 10267: my $filename=$uri;
10268: $uri=~s/\.meta$//;
1.172 www 10269: #
10270: # Is the metadata already cached?
1.177 www 10271: # Look at timestamp of caching
1.172 www 10272: # Everything is cached by the main uri, libraries are never directly cached
10273: #
1.428 albertel 10274: if (!defined($liburi)) {
1.599 albertel 10275: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10276: if (defined($cached)) { return $result->{':'.$what}; }
10277: }
10278: {
1.1069 www 10279: # Imported parts would go here
1.1070 www 10280: my %importedids=();
10281: my @origfileimportpartids=();
1.1069 www 10282: my $importedparts=0;
1.172 www 10283: #
10284: # Is this a recursive call for a library?
10285: #
1.599 albertel 10286: # if (! exists($metacache{$uri})) {
10287: # $metacache{$uri}={};
10288: # }
1.924 albertel 10289: my $cachetime = 60*60;
1.171 www 10290: if ($liburi) {
10291: $liburi=&declutter($liburi);
10292: $filename=$liburi;
1.401 bowersj2 10293: } else {
1.599 albertel 10294: &devalidate_cache_new('meta',$uri);
10295: undef(%metaentry);
1.401 bowersj2 10296: }
1.140 www 10297: my %metathesekeys=();
1.73 www 10298: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10299: my $metastring;
1.1140 www 10300: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10301: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10302: $metastring =
1.929 albertel 10303: &Apache::lonnet::ssi_body($which,
1.924 albertel 10304: ('grade_target' => 'meta'));
10305: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10306: } elsif (($uri !~ m -^(editupload)/-) &&
10307: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10308: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10309: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10310: $metastring=&getfile($file);
1.489 albertel 10311: }
1.208 albertel 10312: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10313: my $token;
1.140 www 10314: undef %metathesekeys;
1.71 www 10315: while ($token=$parser->get_token) {
1.339 albertel 10316: if ($token->[0] eq 'S') {
10317: if (defined($token->[2]->{'package'})) {
1.172 www 10318: #
10319: # This is a package - get package info
10320: #
1.339 albertel 10321: my $package=$token->[2]->{'package'};
10322: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10323: if (defined($token->[2]->{'id'})) {
10324: $keyroot.='_'.$token->[2]->{'id'};
10325: }
1.599 albertel 10326: if ($metaentry{':packages'}) {
10327: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10328: } else {
1.599 albertel 10329: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10330: }
1.736 albertel 10331: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10332: my $part=$keyroot;
10333: $part=~s/^\_//;
1.736 albertel 10334: if ($pack_entry=~/^\Q$package\E\&/ ||
10335: $pack_entry=~/^\Q$package\E_0\&/) {
10336: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10337: # ignore package.tab specified default values
10338: # here &package_tab_default() will fetch those
10339: if ($subp eq 'default') { next; }
1.736 albertel 10340: my $value=$packagetab{$pack_entry};
1.432 albertel 10341: my $unikey;
10342: if ($pack =~ /_0$/) {
10343: $unikey='parameter_0_'.$name;
10344: $part=0;
10345: } else {
10346: $unikey='parameter'.$keyroot.'_'.$name;
10347: }
1.339 albertel 10348: if ($subp eq 'display') {
10349: $value.=' [Part: '.$part.']';
10350: }
1.599 albertel 10351: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10352: $metathesekeys{$unikey}=1;
1.599 albertel 10353: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10354: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10355: }
1.599 albertel 10356: if (defined($metaentry{':'.$unikey.'.default'})) {
10357: $metaentry{':'.$unikey}=
10358: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10359: }
1.339 albertel 10360: }
10361: }
10362: } else {
1.172 www 10363: #
10364: # This is not a package - some other kind of start tag
1.339 albertel 10365: #
10366: my $entry=$token->[1];
1.1068 www 10367: my $unikey='';
1.175 www 10368:
1.339 albertel 10369: if ($entry eq 'import') {
1.175 www 10370: #
10371: # Importing a library here
1.339 albertel 10372: #
1.1067 www 10373: my $location=$parser->get_text('/import');
10374: my $dir=$filename;
10375: $dir=~s|[^/]*$||;
10376: $location=&filelocation($dir,$location);
1.1069 www 10377:
1.1068 www 10378: my $importmode=$token->[2]->{'importmode'};
10379: if ($importmode eq 'problem') {
1.1069 www 10380: # Import as problem/response
1.1068 www 10381: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10382: } elsif ($importmode eq 'part') {
10383: # Import as part(s)
1.1069 www 10384: $importedparts=1;
10385: # We need to get the original file and the imported file to get the part order correct
10386: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10387: # Load and inspect original file
1.1070 www 10388: if ($#origfileimportpartids<0) {
10389: undef(%importedpartids);
10390: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10391: my $origfile=&getfile($origfilelocation);
10392: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10393: }
10394:
1.1069 www 10395: # Load and inspect imported file
10396: my $impfile=&getfile($location);
10397: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10398: if ($#impfilepartids>=0) {
10399: # This problem had parts
1.1070 www 10400: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10401: } else {
10402: # Importing by turning a single problem into a problem part
10403: # It gets the import-tags ID as part-ID
10404: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10405: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10406: }
1.1068 www 10407: } else {
10408: # Normal import
10409: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10410: if (defined($token->[2]->{'id'})) {
10411: $unikey.='_'.$token->[2]->{'id'};
10412: }
1.1067 www 10413: }
10414:
1.339 albertel 10415: if ($depthcount<20) {
1.736 albertel 10416: my $metadata =
10417: &metadata($uri,'keys', $location,$unikey,
10418: $depthcount+1);
10419: foreach my $meta (split(',',$metadata)) {
10420: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10421: $metathesekeys{$meta}=1;
1.339 albertel 10422: }
1.1068 www 10423:
10424: }
1.1067 www 10425: } else {
10426: #
10427: # Not importing, some other kind of non-package, non-library start tag
10428: #
10429: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10430: if (defined($token->[2]->{'id'})) {
10431: $unikey.='_'.$token->[2]->{'id'};
10432: }
1.339 albertel 10433: if (defined($token->[2]->{'name'})) {
10434: $unikey.='_'.$token->[2]->{'name'};
10435: }
10436: $metathesekeys{$unikey}=1;
1.736 albertel 10437: foreach my $param (@{$token->[3]}) {
10438: $metaentry{':'.$unikey.'.'.$param} =
10439: $token->[2]->{$param};
1.339 albertel 10440: }
10441: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10442: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10443: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10444: # only ws inside the tag, and not in default, so use default
10445: # as value
1.599 albertel 10446: $metaentry{':'.$unikey}=$default;
1.908 albertel 10447: } elsif ( $internaltext =~ /\S/ ) {
10448: # something interesting inside the tag
10449: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10450: } else {
1.908 albertel 10451: # no interesting values, don't set a default
1.339 albertel 10452: }
1.172 www 10453: # end of not-a-package not-a-library import
1.339 albertel 10454: }
1.172 www 10455: # end of not-a-package start tag
1.339 albertel 10456: }
1.172 www 10457: # the next is the end of "start tag"
1.339 albertel 10458: }
10459: }
1.483 albertel 10460: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10461: $extension = lc($extension);
10462: if ($extension eq 'htm') { $extension='html'; }
10463:
1.737 albertel 10464: foreach my $key (keys(%packagetab)) {
1.483 albertel 10465: #no specific packages #how's our extension
10466: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10467: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10468: \%metathesekeys);
10469: }
1.883 albertel 10470:
10471: if (!exists($metaentry{':packages'})
10472: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10473: foreach my $key (keys(%packagetab)) {
1.483 albertel 10474: #no specific packages well let's get default then
10475: if ($key!~/^default&/) { next; }
1.488 albertel 10476: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10477: \%metathesekeys);
10478: }
10479: }
1.338 www 10480: # are there custom rights to evaluate
1.599 albertel 10481: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10482:
1.338 www 10483: #
10484: # Importing a rights file here
1.339 albertel 10485: #
10486: unless ($depthcount) {
1.599 albertel 10487: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10488: my $dir=$filename;
10489: $dir=~s|[^/]*$||;
10490: $location=&filelocation($dir,$location);
1.736 albertel 10491: my $rights_metadata =
10492: &metadata($uri,'keys',$location,'_rights',
10493: $depthcount+1);
10494: foreach my $rights (split(',',$rights_metadata)) {
10495: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10496: $metathesekeys{$rights}=1;
1.339 albertel 10497: }
10498: }
10499: }
1.737 albertel 10500: # uniqifiy package listing
10501: my %seen;
10502: my @uniq_packages =
10503: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10504: $metaentry{':packages'} = join(',',@uniq_packages);
10505:
1.1070 www 10506: if ($importedparts) {
10507: # We had imported parts and need to rebuild partorder
10508: $metaentry{':partorder'}='';
10509: $metathesekeys{'partorder'}=1;
10510: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10511: if ($origfileimportpartids[$index] eq 'part') {
10512: # original part, part of the problem
10513: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10514: } else {
10515: # we have imported parts at this position
10516: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10517: }
10518: }
10519: $metaentry{':partorder'}=~s/^\,//;
10520: }
10521:
1.737 albertel 10522: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10523: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10524: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 10525: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10526: # this is the end of "was not already recently cached
1.71 www 10527: }
1.599 albertel 10528: return $metaentry{':'.$what};
1.261 albertel 10529: }
10530:
1.488 albertel 10531: sub metadata_create_package_def {
1.483 albertel 10532: my ($uri,$key,$package,$metathesekeys)=@_;
10533: my ($pack,$name,$subp)=split(/\&/,$key);
10534: if ($subp eq 'default') { next; }
10535:
1.599 albertel 10536: if (defined($metaentry{':packages'})) {
10537: $metaentry{':packages'}.=','.$package;
1.483 albertel 10538: } else {
1.599 albertel 10539: $metaentry{':packages'}=$package;
1.483 albertel 10540: }
10541: my $value=$packagetab{$key};
10542: my $unikey;
10543: $unikey='parameter_0_'.$name;
1.599 albertel 10544: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10545: $$metathesekeys{$unikey}=1;
1.599 albertel 10546: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10547: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10548: }
1.599 albertel 10549: if (defined($metaentry{':'.$unikey.'.default'})) {
10550: $metaentry{':'.$unikey}=
10551: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10552: }
10553: }
10554:
1.261 albertel 10555: sub metadata_generate_part0 {
10556: my ($metadata,$metacache,$uri) = @_;
10557: my %allnames;
1.737 albertel 10558: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10559: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10560: my $part=$$metacache{':'.$metakey.'.part'};
10561: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10562: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10563: $allnames{$name}=$part;
10564: }
10565: }
10566: }
10567: foreach my $name (keys(%allnames)) {
10568: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10569: my $key=":parameter_0_$name";
1.261 albertel 10570: $$metacache{"$key.part"}='0';
10571: $$metacache{"$key.name"}=$name;
1.428 albertel 10572: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10573: $allnames{$name}.'_'.$name.
10574: '.type'};
1.428 albertel 10575: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10576: '.display'};
1.644 www 10577: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10578: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10579: $$metacache{"$key.display"}=$olddis;
10580: }
1.71 www 10581: }
10582:
1.764 albertel 10583: # ------------------------------------------------------ Devalidate title cache
10584:
10585: sub devalidate_title_cache {
10586: my ($url)=@_;
10587: if (!$env{'request.course.id'}) { return; }
10588: my $symb=&symbread($url);
10589: if (!$symb) { return; }
10590: my $key=$env{'request.course.id'}."\0".$symb;
10591: &devalidate_cache_new('title',$key);
10592: }
10593:
1.1014 droeschl 10594: # ------------------------------------------------- Get the title of a course
10595:
10596: sub current_course_title {
10597: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10598: }
1.301 www 10599: # ------------------------------------------------- Get the title of a resource
10600:
10601: sub gettitle {
10602: my $urlsymb=shift;
10603: my $symb=&symbread($urlsymb);
1.534 albertel 10604: if ($symb) {
1.620 albertel 10605: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10606: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10607: if (defined($cached)) {
10608: return $result;
10609: }
1.534 albertel 10610: my ($map,$resid,$url)=&decode_symb($symb);
10611: my $title='';
1.907 albertel 10612: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10613: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10614: } else {
10615: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10616: &GDBM_READER(),0640)) {
10617: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10618: $title=$bighash{'title_'.$mapid.'.'.$resid};
10619: untie(%bighash);
10620: }
1.534 albertel 10621: }
10622: $title=~s/\&colon\;/\:/gs;
10623: if ($title) {
1.1159 www 10624: # Remember both $symb and $title for dynamic metadata
10625: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10626: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10627: # Cache this title and then return it
1.599 albertel 10628: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10629: }
10630: $urlsymb=$url;
10631: }
10632: my $title=&metadata($urlsymb,'title');
10633: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10634: return $title;
1.301 www 10635: }
1.613 albertel 10636:
1.614 albertel 10637: sub get_slot {
10638: my ($which,$cnum,$cdom)=@_;
10639: if (!$cnum || !$cdom) {
1.790 albertel 10640: (undef,my $courseid)=&whichuser();
1.620 albertel 10641: $cdom=$env{'course.'.$courseid.'.domain'};
10642: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10643: }
1.703 albertel 10644: my $key=join("\0",'slots',$cdom,$cnum,$which);
10645: my %slotinfo;
10646: if (exists($remembered{$key})) {
10647: $slotinfo{$which} = $remembered{$key};
10648: } else {
10649: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10650: &Apache::lonhomework::showhash(%slotinfo);
10651: my ($tmp)=keys(%slotinfo);
10652: if ($tmp=~/^error:/) { return (); }
10653: $remembered{$key} = $slotinfo{$which};
10654: }
1.616 albertel 10655: if (ref($slotinfo{$which}) eq 'HASH') {
10656: return %{$slotinfo{$which}};
10657: }
10658: return $slotinfo{$which};
1.614 albertel 10659: }
1.1150 raeburn 10660:
10661: sub get_reservable_slots {
10662: my ($cnum,$cdom,$uname,$udom) = @_;
10663: my $now = time;
10664: my $reservable_info;
10665: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10666: if (exists($remembered{$key})) {
10667: $reservable_info = $remembered{$key};
10668: } else {
10669: my %resv;
10670: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10671: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10672: $reservable_info = \%resv;
10673: $remembered{$key} = $reservable_info;
10674: }
10675: return $reservable_info;
10676: }
10677:
10678: sub get_course_slots {
10679: my ($cnum,$cdom) = @_;
10680: my $hashid=$cnum.':'.$cdom;
10681: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10682: if (defined($cached)) {
10683: if (ref($result) eq 'HASH') {
10684: return %{$result};
10685: }
10686: } else {
10687: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10688: my ($tmp) = keys(%slots);
10689: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 10690: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10691: return %slots;
10692: }
10693: }
10694: return;
10695: }
10696:
10697: sub devalidate_slots_cache {
10698: my ($cnum,$cdom)=@_;
10699: my $hashid=$cnum.':'.$cdom;
10700: &devalidate_cache_new('allslots',$hashid);
10701: }
10702:
1.1172.2.8 raeburn 10703: sub get_coursechange {
10704: my ($cdom,$cnum) = @_;
10705: if ($cdom eq '' || $cnum eq '') {
10706: return unless ($env{'request.course.id'});
10707: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10708: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10709: }
10710: my $hashid=$cdom.'_'.$cnum;
10711: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10712: if ((defined($cached)) && ($change ne '')) {
10713: return $change;
10714: } else {
10715: my %crshash;
10716: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10717: if ($crshash{'internal.contentchange'} eq '') {
10718: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10719: if ($change eq '') {
10720: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10721: $change = $crshash{'internal.created'};
10722: }
10723: } else {
10724: $change = $crshash{'internal.contentchange'};
10725: }
10726: my $cachetime = 600;
10727: &do_cache_new('crschange',$hashid,$change,$cachetime);
10728: }
10729: return $change;
10730: }
10731:
10732: sub devalidate_coursechange_cache {
10733: my ($cnum,$cdom)=@_;
10734: my $hashid=$cnum.':'.$cdom;
10735: &devalidate_cache_new('crschange',$hashid);
10736: }
10737:
1.31 www 10738: # ------------------------------------------------- Update symbolic store links
10739:
10740: sub symblist {
10741: my ($mapname,%newhash)=@_;
1.438 www 10742: $mapname=&deversion(&declutter($mapname));
1.31 www 10743: my %hash;
1.620 albertel 10744: if (($env{'request.course.fn'}) && (%newhash)) {
10745: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10746: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10747: foreach my $url (keys(%newhash)) {
1.711 albertel 10748: next if ($url eq 'last_known'
10749: && $env{'form.no_update_last_known'});
10750: $hash{declutter($url)}=&encode_symb($mapname,
10751: $newhash{$url}->[1],
10752: $newhash{$url}->[0]);
1.191 harris41 10753: }
1.31 www 10754: if (untie(%hash)) {
10755: return 'ok';
10756: }
10757: }
10758: }
10759: return 'error';
1.212 www 10760: }
10761:
10762: # --------------------------------------------------------------- Verify a symb
10763:
10764: sub symbverify {
1.1172.2.11 raeburn 10765: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10766: my $thisfn=$thisurl;
1.439 www 10767: $thisfn=&declutter($thisfn);
1.215 www 10768: # direct jump to resource in page or to a sequence - will construct own symbs
10769: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10770: # check URL part
1.409 www 10771: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10772:
1.431 www 10773: unless ($url eq $thisfn) { return 0; }
1.213 www 10774:
1.216 www 10775: $symb=&symbclean($symb);
1.510 www 10776: $thisurl=&deversion($thisurl);
1.439 www 10777: $thisfn=&deversion($thisfn);
1.213 www 10778:
10779: my %bighash;
10780: my $okay=0;
1.431 www 10781:
1.620 albertel 10782: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10783: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 10784: my $noclutter;
1.1032 raeburn 10785: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10786: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 10787: if ($map =~ m{^uploaded/.+\.page$}) {
10788: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10789: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10790: $noclutter = 1;
10791: }
10792: }
10793: my $ids;
10794: if ($noclutter) {
10795: $ids=$bighash{'ids_'.$thisurl};
10796: } else {
10797: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10798: }
1.1102 raeburn 10799: unless ($ids) {
1.1172.2.13 raeburn 10800: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 10801: $ids=$bighash{$idkey};
1.216 www 10802: }
10803: if ($ids) {
10804: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 10805: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10806: $symb =~ s/\?.+$//;
10807: }
1.800 albertel 10808: foreach my $id (split(/\,/,$ids)) {
10809: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10810: if (
10811: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 10812: eq $symb) {
1.1172.2.11 raeburn 10813: if (ref($encstate)) {
10814: $$encstate = $bighash{'encrypted_'.$id};
10815: }
1.1172.2.13 raeburn 10816: if (($env{'request.role.adv'}) ||
10817: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 10818: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 10819: $okay=1;
10820: last;
10821: }
10822: }
10823: }
1.216 www 10824: }
1.213 www 10825: untie(%bighash);
10826: }
10827: return $okay;
1.31 www 10828: }
10829:
1.210 www 10830: # --------------------------------------------------------------- Clean-up symb
10831:
10832: sub symbclean {
10833: my $symb=shift;
1.568 albertel 10834: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10835: # remove version from map
10836: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10837:
1.210 www 10838: # remove version from URL
10839: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10840:
1.507 www 10841: # remove wrapper
10842:
1.510 www 10843: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10844: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10845: return $symb;
1.409 www 10846: }
10847:
10848: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10849:
10850: sub encode_symb {
10851: my ($map,$resid,$url)=@_;
10852: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10853: }
1.409 www 10854:
10855: sub decode_symb {
1.568 albertel 10856: my $symb=shift;
10857: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10858: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10859: return (&fixversion($map),$resid,&fixversion($url));
10860: }
10861:
10862: sub fixversion {
10863: my $fn=shift;
1.609 banghart 10864: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10865: my %bighash;
10866: my $uri=&clutter($fn);
1.620 albertel 10867: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10868: # is this cached?
1.599 albertel 10869: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10870: if (defined($cached)) { return $result; }
10871: # unfortunately not cached, or expired
1.620 albertel 10872: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10873: &GDBM_READER(),0640)) {
10874: if ($bighash{'version_'.$uri}) {
10875: my $version=$bighash{'version_'.$uri};
1.444 www 10876: unless (($version eq 'mostrecent') ||
10877: ($version==&getversion($uri))) {
1.440 www 10878: $uri=~s/\.(\w+)$/\.$version\.$1/;
10879: }
10880: }
10881: untie %bighash;
1.413 www 10882: }
1.599 albertel 10883: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10884: }
10885:
10886: sub deversion {
10887: my $url=shift;
10888: $url=~s/\.\d+\.(\w+)$/\.$1/;
10889: return $url;
1.210 www 10890: }
10891:
1.31 www 10892: # ------------------------------------------------------ Return symb list entry
10893:
10894: sub symbread {
1.249 www 10895: my ($thisfn,$donotrecurse)=@_;
1.1172.2.13 raeburn 10896: my $cache_str;
10897: if ($thisfn ne '') {
10898: $cache_str='request.symbread.cached.'.$thisfn;
10899: if ($env{$cache_str} ne '') {
1.1172.2.8 raeburn 10900: return $env{$cache_str};
10901: }
1.1172.2.13 raeburn 10902: } else {
1.242 www 10903: # no filename provided? try from environment
1.620 albertel 10904: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 10905: return $env{$cache_str}=&symbclean($env{'request.symb'});
10906: }
10907: $thisfn=$env{'request.filename'};
1.44 www 10908: }
1.569 albertel 10909: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10910: # is that filename actually a symb? Verify, clean, and return
10911: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10912: if (&symbverify($thisfn,$1)) {
1.620 albertel 10913: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10914: }
1.242 www 10915: }
1.44 www 10916: $thisfn=declutter($thisfn);
1.31 www 10917: my %hash;
1.37 www 10918: my %bighash;
10919: my $syval='';
1.620 albertel 10920: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10921: my $targetfn = $thisfn;
1.609 banghart 10922: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10923: $targetfn = 'adm/wrapper/'.$thisfn;
10924: }
1.687 albertel 10925: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10926: $targetfn=$1;
10927: }
1.620 albertel 10928: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10929: &GDBM_READER(),0640)) {
1.481 raeburn 10930: $syval=$hash{$targetfn};
1.37 www 10931: untie(%hash);
10932: }
10933: # ---------------------------------------------------------- There was an entry
10934: if ($syval) {
1.601 albertel 10935: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10936: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10937: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10938: #return $env{$cache_str}='';
1.601 albertel 10939: #}
10940: #$syval.=$1;
10941: #}
1.37 www 10942: } else {
10943: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10944: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10945: &GDBM_READER(),0640)) {
1.37 www 10946: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10947: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10948: unless ($ids) {
10949: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10950: }
10951: unless ($ids) {
10952: # alias?
10953: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10954: }
1.37 www 10955: if ($ids) {
10956: # ------------------------------------------------------------------- Has ID(s)
10957: my @possibilities=split(/\,/,$ids);
1.39 www 10958: if ($#possibilities==0) {
10959: # ----------------------------------------------- There is only one possibility
1.37 www 10960: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10961: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10962: $resid,$thisfn);
1.249 www 10963: } elsif (!$donotrecurse) {
1.39 www 10964: # ------------------------------------------ There is more than one possibility
10965: my $realpossible=0;
1.800 albertel 10966: foreach my $id (@possibilities) {
10967: my $file=$bighash{'src_'.$id};
1.39 www 10968: if (&allowed('bre',$file)) {
1.800 albertel 10969: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10970: if ($bighash{'map_type_'.$mapid} ne 'page') {
10971: $realpossible++;
1.626 albertel 10972: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10973: $resid,$thisfn);
1.39 www 10974: }
10975: }
1.191 harris41 10976: }
1.39 www 10977: if ($realpossible!=1) { $syval=''; }
1.249 www 10978: } else {
10979: $syval='';
1.37 www 10980: }
10981: }
10982: untie(%bighash)
1.481 raeburn 10983: }
1.31 www 10984: }
1.62 www 10985: if ($syval) {
1.620 albertel 10986: return $env{$cache_str}=$syval;
1.62 www 10987: }
1.31 www 10988: }
1.949 raeburn 10989: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10990: return $env{$cache_str}='';
1.31 www 10991: }
10992:
10993: # ---------------------------------------------------------- Return random seed
10994:
1.32 www 10995: sub numval {
10996: my $txt=shift;
10997: $txt=~tr/A-J/0-9/;
10998: $txt=~tr/a-j/0-9/;
10999: $txt=~tr/K-T/0-9/;
11000: $txt=~tr/k-t/0-9/;
11001: $txt=~tr/U-Z/0-5/;
11002: $txt=~tr/u-z/0-5/;
11003: $txt=~s/\D//g;
1.564 albertel 11004: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11005: return int($txt);
1.368 albertel 11006: }
11007:
1.484 albertel 11008: sub numval2 {
11009: my $txt=shift;
11010: $txt=~tr/A-J/0-9/;
11011: $txt=~tr/a-j/0-9/;
11012: $txt=~tr/K-T/0-9/;
11013: $txt=~tr/k-t/0-9/;
11014: $txt=~tr/U-Z/0-5/;
11015: $txt=~tr/u-z/0-5/;
11016: $txt=~s/\D//g;
11017: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11018: my $total;
11019: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11020: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11021: return int($total);
11022: }
11023:
1.575 albertel 11024: sub numval3 {
11025: use integer;
11026: my $txt=shift;
11027: $txt=~tr/A-J/0-9/;
11028: $txt=~tr/a-j/0-9/;
11029: $txt=~tr/K-T/0-9/;
11030: $txt=~tr/k-t/0-9/;
11031: $txt=~tr/U-Z/0-5/;
11032: $txt=~tr/u-z/0-5/;
11033: $txt=~s/\D//g;
11034: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11035: my $total;
11036: foreach my $val (@txts) { $total+=$val; }
11037: if ($_64bit) { $total=(($total<<32)>>32); }
11038: return $total;
11039: }
11040:
1.675 albertel 11041: sub digest {
11042: my ($data)=@_;
11043: my $digest=&Digest::MD5::md5($data);
11044: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11045: my ($e,$f);
11046: {
11047: use integer;
11048: $e=($a+$b);
11049: $f=($c+$d);
11050: if ($_64bit) {
11051: $e=(($e<<32)>>32);
11052: $f=(($f<<32)>>32);
11053: }
11054: }
11055: if (wantarray) {
11056: return ($e,$f);
11057: } else {
11058: my $g;
11059: {
11060: use integer;
11061: $g=($e+$f);
11062: if ($_64bit) {
11063: $g=(($g<<32)>>32);
11064: }
11065: }
11066: return $g;
11067: }
11068: }
11069:
1.368 albertel 11070: sub latest_rnd_algorithm_id {
1.675 albertel 11071: return '64bit5';
1.366 albertel 11072: }
1.32 www 11073:
1.503 albertel 11074: sub get_rand_alg {
11075: my ($courseid)=@_;
1.790 albertel 11076: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11077: if ($courseid) {
1.620 albertel 11078: return $env{"course.$courseid.rndseed"};
1.503 albertel 11079: }
11080: return &latest_rnd_algorithm_id();
11081: }
11082:
1.562 albertel 11083: sub validCODE {
11084: my ($CODE)=@_;
11085: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11086: return 0;
11087: }
11088:
1.491 albertel 11089: sub getCODE {
1.620 albertel 11090: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11091: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11092: defined($Apache::lonhomework::parsing_a_task) ) &&
11093: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11094: return $Apache::lonhomework::history{'resource.CODE'};
11095: }
11096: return undef;
11097: }
1.1133 foxr 11098: #
11099: # Determines the random seed for a specific context:
11100: #
11101: # parameters:
11102: # symb - in course context the symb for the seed.
11103: # course_id - The course id of the form domain_coursenum.
11104: # domain - Domain for the user.
11105: # course - Course for the user.
11106: # cenv - environment of the course.
11107: #
11108: # NOTE:
11109: # All parameters are picked out of the environment if missing
11110: # or not defined.
11111: # If a symb cannot be determined the current time is used instead.
11112: #
11113: # For a given well defined symb, courside, domain, username,
11114: # and course environment, the seed is reproducible.
11115: #
1.31 www 11116: sub rndseed {
1.1133 foxr 11117: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11118: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11119: if (!defined($symb)) {
1.366 albertel 11120: unless ($symb=$wsymb) { return time; }
11121: }
1.1146 foxr 11122: if (!defined $courseid) {
11123: $courseid=$wcourseid;
11124: }
11125: if (!defined $domain) { $domain=$wdomain; }
11126: if (!defined $username) { $username=$wusername }
1.1133 foxr 11127:
11128: my $which;
11129: if (defined($cenv->{'rndseed'})) {
11130: $which = $cenv->{'rndseed'};
11131: } else {
11132: $which =&get_rand_alg($courseid);
11133: }
1.491 albertel 11134: if (defined(&getCODE())) {
1.675 albertel 11135: if ($which eq '64bit5') {
11136: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11137: } elsif ($which eq '64bit4') {
1.575 albertel 11138: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11139: } else {
11140: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11141: }
1.675 albertel 11142: } elsif ($which eq '64bit5') {
11143: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11144: } elsif ($which eq '64bit4') {
11145: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11146: } elsif ($which eq '64bit3') {
11147: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11148: } elsif ($which eq '64bit2') {
11149: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11150: } elsif ($which eq '64bit') {
11151: return &rndseed_64bit($symb,$courseid,$domain,$username);
11152: }
11153: return &rndseed_32bit($symb,$courseid,$domain,$username);
11154: }
11155:
11156: sub rndseed_32bit {
11157: my ($symb,$courseid,$domain,$username)=@_;
11158: {
11159: use integer;
11160: my $symbchck=unpack("%32C*",$symb) << 27;
11161: my $symbseed=numval($symb) << 22;
11162: my $namechck=unpack("%32C*",$username) << 17;
11163: my $nameseed=numval($username) << 12;
11164: my $domainseed=unpack("%32C*",$domain) << 7;
11165: my $courseseed=unpack("%32C*",$courseid);
11166: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11167: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11168: #&logthis("rndseed :$num:$symb");
1.564 albertel 11169: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11170: return $num;
11171: }
11172: }
11173:
11174: sub rndseed_64bit {
11175: my ($symb,$courseid,$domain,$username)=@_;
11176: {
11177: use integer;
11178: my $symbchck=unpack("%32S*",$symb) << 21;
11179: my $symbseed=numval($symb) << 10;
11180: my $namechck=unpack("%32S*",$username);
11181:
11182: my $nameseed=numval($username) << 21;
11183: my $domainseed=unpack("%32S*",$domain) << 10;
11184: my $courseseed=unpack("%32S*",$courseid);
11185:
11186: my $num1=$symbchck+$symbseed+$namechck;
11187: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11188: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11189: #&logthis("rndseed :$num:$symb");
1.564 albertel 11190: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11191: return "$num1,$num2";
1.155 albertel 11192: }
1.366 albertel 11193: }
11194:
1.443 albertel 11195: sub rndseed_64bit2 {
11196: my ($symb,$courseid,$domain,$username)=@_;
11197: {
11198: use integer;
11199: # strings need to be an even # of cahracters long, it it is odd the
11200: # last characters gets thrown away
11201: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11202: my $symbseed=numval($symb) << 10;
11203: my $namechck=unpack("%32S*",$username.' ');
11204:
11205: my $nameseed=numval($username) << 21;
1.501 albertel 11206: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11207: my $courseseed=unpack("%32S*",$courseid.' ');
11208:
11209: my $num1=$symbchck+$symbseed+$namechck;
11210: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11211: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11212: #&logthis("rndseed :$num:$symb");
1.803 albertel 11213: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11214: return "$num1,$num2";
11215: }
11216: }
11217:
11218: sub rndseed_64bit3 {
11219: my ($symb,$courseid,$domain,$username)=@_;
11220: {
11221: use integer;
11222: # strings need to be an even # of cahracters long, it it is odd the
11223: # last characters gets thrown away
11224: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11225: my $symbseed=numval2($symb) << 10;
11226: my $namechck=unpack("%32S*",$username.' ');
11227:
11228: my $nameseed=numval2($username) << 21;
1.443 albertel 11229: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11230: my $courseseed=unpack("%32S*",$courseid.' ');
11231:
11232: my $num1=$symbchck+$symbseed+$namechck;
11233: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11234: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11235: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11236: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11237:
1.503 albertel 11238: return "$num1:$num2";
1.443 albertel 11239: }
11240: }
11241:
1.575 albertel 11242: sub rndseed_64bit4 {
11243: my ($symb,$courseid,$domain,$username)=@_;
11244: {
11245: use integer;
11246: # strings need to be an even # of cahracters long, it it is odd the
11247: # last characters gets thrown away
11248: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11249: my $symbseed=numval3($symb) << 10;
11250: my $namechck=unpack("%32S*",$username.' ');
11251:
11252: my $nameseed=numval3($username) << 21;
11253: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11254: my $courseseed=unpack("%32S*",$courseid.' ');
11255:
11256: my $num1=$symbchck+$symbseed+$namechck;
11257: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11258: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11259: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11260: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11261:
1.575 albertel 11262: return "$num1:$num2";
11263: }
11264: }
11265:
1.675 albertel 11266: sub rndseed_64bit5 {
11267: my ($symb,$courseid,$domain,$username)=@_;
11268: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11269: return "$num1:$num2";
11270: }
11271:
1.366 albertel 11272: sub rndseed_CODE_64bit {
11273: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11274: {
1.366 albertel 11275: use integer;
1.443 albertel 11276: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11277: my $symbseed=numval2($symb);
1.491 albertel 11278: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11279: my $CODEseed=numval(&getCODE());
1.443 albertel 11280: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11281: my $num1=$symbseed+$CODEchck;
11282: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11283: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11284: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11285: if ($_64bit) { $num1=(($num1<<32)>>32); }
11286: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11287: return "$num1:$num2";
1.366 albertel 11288: }
11289: }
11290:
1.575 albertel 11291: sub rndseed_CODE_64bit4 {
11292: my ($symb,$courseid,$domain,$username)=@_;
11293: {
11294: use integer;
11295: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11296: my $symbseed=numval3($symb);
11297: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11298: my $CODEseed=numval3(&getCODE());
11299: my $courseseed=unpack("%32S*",$courseid.' ');
11300: my $num1=$symbseed+$CODEchck;
11301: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11302: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11303: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11304: if ($_64bit) { $num1=(($num1<<32)>>32); }
11305: if ($_64bit) { $num2=(($num2<<32)>>32); }
11306: return "$num1:$num2";
11307: }
11308: }
11309:
1.675 albertel 11310: sub rndseed_CODE_64bit5 {
11311: my ($symb,$courseid,$domain,$username)=@_;
11312: my $code = &getCODE();
11313: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11314: return "$num1:$num2";
11315: }
11316:
1.366 albertel 11317: sub setup_random_from_rndseed {
11318: my ($rndseed)=@_;
1.503 albertel 11319: if ($rndseed =~/([,:])/) {
11320: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 11321: &Math::Random::random_set_seed(abs($num1),abs($num2));
11322: } else {
11323: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11324: }
1.36 albertel 11325: }
11326:
1.474 albertel 11327: sub latest_receipt_algorithm_id {
1.835 albertel 11328: return 'receipt3';
1.474 albertel 11329: }
11330:
1.480 www 11331: sub recunique {
11332: my $fucourseid=shift;
11333: my $unique;
1.835 albertel 11334: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11335: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11336: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11337: } else {
11338: $unique=$perlvar{'lonReceipt'};
11339: }
11340: return unpack("%32C*",$unique);
11341: }
11342:
11343: sub recprefix {
11344: my $fucourseid=shift;
11345: my $prefix;
1.835 albertel 11346: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11347: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11348: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11349: } else {
11350: $prefix=$perlvar{'lonHostID'};
11351: }
11352: return unpack("%32C*",$prefix);
11353: }
11354:
1.76 www 11355: sub ireceipt {
1.474 albertel 11356: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11357:
11358: my $return =&recprefix($fucourseid).'-';
11359:
11360: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11361: $env{'request.state'} eq 'construct') {
11362: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11363: return $return;
11364: }
11365:
1.76 www 11366: my $cuname=unpack("%32C*",$funame);
11367: my $cudom=unpack("%32C*",$fudom);
11368: my $cucourseid=unpack("%32C*",$fucourseid);
11369: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11370: my $cunique=&recunique($fucourseid);
1.474 albertel 11371: my $cpart=unpack("%32S*",$part);
1.835 albertel 11372: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11373:
1.790 albertel 11374: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11375:
11376: $return.= ($cunique%$cuname+
11377: $cunique%$cudom+
11378: $cusymb%$cuname+
11379: $cusymb%$cudom+
11380: $cucourseid%$cuname+
11381: $cucourseid%$cudom+
11382: $cpart%$cuname+
11383: $cpart%$cudom);
11384: } else {
11385: $return.= ($cunique%$cuname+
11386: $cunique%$cudom+
11387: $cusymb%$cuname+
11388: $cusymb%$cudom+
11389: $cucourseid%$cuname+
11390: $cucourseid%$cudom);
11391: }
11392: return $return;
1.76 www 11393: }
11394:
11395: sub receipt {
1.474 albertel 11396: my ($part)=@_;
1.790 albertel 11397: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11398: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11399: }
1.260 ng 11400:
1.790 albertel 11401: sub whichuser {
11402: my ($passedsymb)=@_;
11403: my ($symb,$courseid,$domain,$name,$publicuser);
11404: if (defined($env{'form.grade_symb'})) {
11405: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11406: my $allowed=&allowed('vgr',$tmp_courseid);
11407: if (!$allowed &&
11408: exists($env{'request.course.sec'}) &&
11409: $env{'request.course.sec'} !~ /^\s*$/) {
11410: $allowed=&allowed('vgr',$tmp_courseid.
11411: '/'.$env{'request.course.sec'});
11412: }
11413: if ($allowed) {
11414: ($symb)=&get_env_multiple('form.grade_symb');
11415: $courseid=$tmp_courseid;
11416: ($domain)=&get_env_multiple('form.grade_domain');
11417: ($name)=&get_env_multiple('form.grade_username');
11418: return ($symb,$courseid,$domain,$name,$publicuser);
11419: }
11420: }
11421: if (!$passedsymb) {
11422: $symb=&symbread();
11423: } else {
11424: $symb=$passedsymb;
11425: }
11426: $courseid=$env{'request.course.id'};
11427: $domain=$env{'user.domain'};
11428: $name=$env{'user.name'};
11429: if ($name eq 'public' && $domain eq 'public') {
11430: if (!defined($env{'form.username'})) {
11431: $env{'form.username'}.=time.rand(10000000);
11432: }
11433: $name.=$env{'form.username'};
11434: }
11435: return ($symb,$courseid,$domain,$name,$publicuser);
11436:
11437: }
11438:
1.36 albertel 11439: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11440: # returns either the contents of the file or
11441: # -1 if the file doesn't exist
1.481 raeburn 11442: #
11443: # if the target is a file that was uploaded via DOCS,
11444: # a check will be made to see if a current copy exists on the local server,
11445: # if it does this will be served, otherwise a copy will be retrieved from
11446: # the home server for the course and stored in /home/httpd/html/userfiles on
11447: # the local server.
1.472 albertel 11448:
1.36 albertel 11449: sub getfile {
1.538 albertel 11450: my ($file) = @_;
1.609 banghart 11451: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11452: &repcopy($file);
11453: return &readfile($file);
11454: }
11455:
11456: sub repcopy_userfile {
11457: my ($file)=@_;
1.1142 raeburn 11458: my $londocroot = $perlvar{'lonDocRoot'};
11459: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11460: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11461: my ($cdom,$cnum,$filename) =
1.811 albertel 11462: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11463: my $uri="/uploaded/$cdom/$cnum/$filename";
11464: if (-e "$file") {
1.828 www 11465: # we already have a local copy, check it out
1.538 albertel 11466: my @fileinfo = stat($file);
1.828 www 11467: my $rtncode;
11468: my $info;
1.538 albertel 11469: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11470: if ($lwpresp ne 'ok') {
1.828 www 11471: # there is no such file anymore, even though we had a local copy
1.482 albertel 11472: if ($rtncode eq '404') {
1.538 albertel 11473: unlink($file);
1.482 albertel 11474: }
11475: return -1;
11476: }
11477: if ($info < $fileinfo[9]) {
1.828 www 11478: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11479: return 'ok';
1.828 www 11480: } else {
11481: # the file is outdated, get rid of it
11482: unlink($file);
1.482 albertel 11483: }
1.828 www 11484: }
11485: # one way or the other, at this point, we don't have the file
11486: # construct the correct path for the file
11487: my @parts = ($cdom,$cnum);
11488: if ($filename =~ m|^(.+)/[^/]+$|) {
11489: push @parts, split(/\//,$1);
11490: }
11491: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11492: foreach my $part (@parts) {
11493: $path .= '/'.$part;
11494: if (!-e $path) {
11495: mkdir($path,0770);
1.482 albertel 11496: }
11497: }
1.828 www 11498: # now the path exists for sure
11499: # get a user agent
11500: my $ua=new LWP::UserAgent;
11501: my $transferfile=$file.'.in.transfer';
11502: # FIXME: this should flock
11503: if (-e $transferfile) { return 'ok'; }
11504: my $request;
11505: $uri=~s/^\///;
1.980 raeburn 11506: my $homeserver = &homeserver($cnum,$cdom);
11507: my $protocol = $protocol{$homeserver};
11508: $protocol = 'http' if ($protocol ne 'https');
11509: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11510: my $response=$ua->request($request,$transferfile);
11511: # did it work?
11512: if ($response->is_error()) {
11513: unlink($transferfile);
11514: &logthis("Userfile repcopy failed for $uri");
11515: return -1;
11516: }
11517: # worked, rename the transfer file
11518: rename($transferfile,$file);
1.607 raeburn 11519: return 'ok';
1.481 raeburn 11520: }
11521:
1.517 albertel 11522: sub tokenwrapper {
11523: my $uri=shift;
1.980 raeburn 11524: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11525: $uri=~s|^/||;
1.620 albertel 11526: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11527: my $token=$1;
1.552 albertel 11528: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11529: if ($udom && $uname && $file) {
11530: $file=~s|(\?\.*)*$||;
1.949 raeburn 11531: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11532: my $homeserver = &homeserver($uname,$udom);
11533: my $protocol = $protocol{$homeserver};
11534: $protocol = 'http' if ($protocol ne 'https');
11535: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11536: (($uri=~/\?/)?'&':'?').'token='.$token.
11537: '&tokenissued='.$perlvar{'lonHostID'};
11538: } else {
11539: return '/adm/notfound.html';
11540: }
11541: }
11542:
1.828 www 11543: # call with reqtype HEAD: get last modification time
11544: # call with reqtype GET: get the file contents
11545: # Do not call this with reqtype GET for large files! It loads everything into memory
11546: #
1.481 raeburn 11547: sub getuploaded {
11548: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11549: $uri=~s/^\///;
1.980 raeburn 11550: my $homeserver = &homeserver($cnum,$cdom);
11551: my $protocol = $protocol{$homeserver};
11552: $protocol = 'http' if ($protocol ne 'https');
11553: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11554: my $ua=new LWP::UserAgent;
11555: my $request=new HTTP::Request($reqtype,$uri);
11556: my $response=$ua->request($request);
11557: $$rtncode = $response->code;
1.482 albertel 11558: if (! $response->is_success()) {
11559: return 'failed';
11560: }
11561: if ($reqtype eq 'HEAD') {
1.486 www 11562: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11563: } elsif ($reqtype eq 'GET') {
11564: $$info = $response->content;
1.472 albertel 11565: }
1.482 albertel 11566: return 'ok';
1.36 albertel 11567: }
11568:
1.481 raeburn 11569: sub readfile {
11570: my $file = shift;
11571: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11572: my $fh;
11573: open($fh,"<$file");
11574: my $a='';
1.800 albertel 11575: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11576: return $a;
11577: }
11578:
1.36 albertel 11579: sub filelocation {
1.590 banghart 11580: my ($dir,$file) = @_;
11581: my $location;
11582: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11583:
11584: if ($file =~ m-^/adm/-) {
11585: $file=~s-^/adm/wrapper/-/-;
11586: $file=~s-^/adm/coursedocs/showdoc/-/-;
11587: }
1.882 albertel 11588:
1.1139 www 11589: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11590: $location = $file;
1.609 banghart 11591: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11592: my ($udom,$uname,$filename)=
1.811 albertel 11593: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11594: my $home=&homeserver($uname,$udom);
11595: my $is_me=0;
11596: my @ids=¤t_machine_ids();
11597: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11598: if ($is_me) {
1.1117 foxr 11599: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11600: } else {
11601: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11602: $udom.'/'.$uname.'/'.$filename;
11603: }
1.882 albertel 11604: } elsif ($file =~ m-^/adm/-) {
11605: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11606: } else {
11607: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11608: $file=~s:^/(res|priv)/:/:;
11609: my $space=$1;
1.590 banghart 11610: if ( !( $file =~ m:^/:) ) {
11611: $location = $dir. '/'.$file;
11612: } else {
1.1142 raeburn 11613: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11614: }
1.59 albertel 11615: }
1.590 banghart 11616: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11617: while ($location=~m{/\.\./}) {
11618: if ($location =~ m{/[^/]+/\.\./}) {
11619: $location=~ s{/[^/]+/\.\./}{/}g;
11620: } else {
11621: $location=~ s{/\.\./}{/}g;
11622: }
11623: } #remove dir/..
1.590 banghart 11624: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11625: return $location;
1.46 www 11626: }
1.36 albertel 11627:
1.46 www 11628: sub hreflocation {
11629: my ($dir,$file)=@_;
1.980 raeburn 11630: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11631: $file=filelocation($dir,$file);
1.700 albertel 11632: } elsif ($file=~m-^/adm/-) {
11633: $file=~s-^/adm/wrapper/-/-;
11634: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11635: }
11636: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11637: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11638: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11639: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11640: {/uploaded/$1/$2/}x;
1.46 www 11641: }
1.913 albertel 11642: if ($file=~ m{^/userfiles/}) {
11643: $file =~ s{^/userfiles/}{/uploaded/};
11644: }
1.462 albertel 11645: return $file;
1.465 albertel 11646: }
11647:
1.1139 www 11648:
11649:
11650:
11651:
1.465 albertel 11652: sub current_machine_domains {
1.853 albertel 11653: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11654: }
11655:
11656: sub machine_domains {
11657: my ($hostname) = @_;
1.465 albertel 11658: my @domains;
1.838 albertel 11659: my %hostname = &all_hostnames();
1.465 albertel 11660: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11661: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11662: if ($hostname eq $name) {
1.844 albertel 11663: push(@domains,&host_domain($id));
1.465 albertel 11664: }
11665: }
11666: return @domains;
11667: }
11668:
11669: sub current_machine_ids {
1.853 albertel 11670: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11671: }
11672:
11673: sub machine_ids {
11674: my ($hostname) = @_;
11675: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11676: my @ids;
1.888 albertel 11677: my %name_to_host = &all_names();
1.889 albertel 11678: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11679: return @{ $name_to_host{$hostname} };
11680: }
11681: return;
1.31 www 11682: }
11683:
1.824 raeburn 11684: sub additional_machine_domains {
11685: my @domains;
11686: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11687: while( my $line = <$fh>) {
11688: $line =~ s/\s//g;
11689: push(@domains,$line);
11690: }
11691: return @domains;
11692: }
11693:
11694: sub default_login_domain {
11695: my $domain = $perlvar{'lonDefDomain'};
11696: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11697: foreach my $posdom (¤t_machine_domains(),
11698: &additional_machine_domains()) {
11699: if (lc($posdom) eq lc($testdomain)) {
11700: $domain=$posdom;
11701: last;
11702: }
11703: }
11704: return $domain;
11705: }
11706:
1.31 www 11707: # ------------------------------------------------------------- Declutters URLs
11708:
11709: sub declutter {
11710: my $thisfn=shift;
1.569 albertel 11711: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 11712: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 11713: $thisfn=~s/^\///;
1.697 albertel 11714: $thisfn=~s|^adm/wrapper/||;
11715: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11716: $thisfn=~s/^res\///;
1.1172 bisitz 11717: $thisfn=~s/^priv\///;
1.1032 raeburn 11718: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11719: $thisfn=~s/\?.+$//;
11720: }
1.268 www 11721: return $thisfn;
11722: }
11723:
11724: # ------------------------------------------------------------- Clutter up URLs
11725:
11726: sub clutter {
11727: my $thisfn='/'.&declutter(shift);
1.887 albertel 11728: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11729: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11730: $thisfn='/res'.$thisfn;
11731: }
1.1031 raeburn 11732: if ($thisfn !~m|^/adm|) {
11733: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11734: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11735: } else {
11736: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11737: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11738: if ($embstyle eq 'ssi'
11739: || ($embstyle eq 'hdn')
11740: || ($embstyle eq 'rat')
11741: || ($embstyle eq 'prv')
11742: || ($embstyle eq 'ign')) {
11743: #do nothing with these
11744: } elsif (($embstyle eq 'img')
1.695 albertel 11745: || ($embstyle eq 'emb')
11746: || ($embstyle eq 'wrp')) {
11747: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11748: } elsif ($embstyle eq 'unk'
11749: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11750: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11751: } else {
1.718 www 11752: # &logthis("Got a blank emb style");
1.695 albertel 11753: }
1.694 albertel 11754: }
11755: }
1.31 www 11756: return $thisfn;
1.12 www 11757: }
11758:
1.787 albertel 11759: sub clutter_with_no_wrapper {
11760: my $uri = &clutter(shift);
11761: if ($uri =~ m-^/adm/-) {
11762: $uri =~ s-^/adm/wrapper/-/-;
11763: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11764: }
11765: return $uri;
11766: }
11767:
1.557 albertel 11768: sub freeze_escape {
11769: my ($value)=@_;
11770: if (ref($value)) {
11771: $value=&nfreeze($value);
11772: return '__FROZEN__'.&escape($value);
11773: }
11774: return &escape($value);
11775: }
11776:
1.11 www 11777:
1.557 albertel 11778: sub thaw_unescape {
11779: my ($value)=@_;
11780: if ($value =~ /^__FROZEN__/) {
11781: substr($value,0,10,undef);
11782: $value=&unescape($value);
11783: return &thaw($value);
11784: }
11785: return &unescape($value);
11786: }
11787:
1.436 albertel 11788: sub correct_line_ends {
11789: my ($result)=@_;
11790: $$result =~s/\r\n/\n/mg;
11791: $$result =~s/\r/\n/mg;
1.415 albertel 11792: }
1.1 albertel 11793: # ================================================================ Main Program
11794:
1.184 www 11795: sub goodbye {
1.204 albertel 11796: &logthis("Starting Shut down");
1.443 albertel 11797: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11798: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11799: #converted
1.599 albertel 11800: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11801: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11802: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11803: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11804: #1.1 only
1.870 albertel 11805: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11806: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11807: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11808: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11809: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11810: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11811: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11812: &flushcourselogs();
11813: &logthis("Shutting down");
11814: }
11815:
1.852 albertel 11816: sub get_dns {
1.1172.2.17 raeburn 11817: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11818: if (!$ignore_cache) {
11819: my ($content,$cached)=
11820: &Apache::lonnet::is_cached_new('dns',$url);
11821: if ($cached) {
1.1172.2.17 raeburn 11822: &$func($content,$hashref);
1.869 albertel 11823: return;
11824: }
11825: }
11826:
11827: my %alldns;
1.852 albertel 11828: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11829: foreach my $dns (<$config>) {
11830: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11831: my $line = $1;
11832: my ($host,$protocol) = split(/:/,$line);
11833: if ($protocol ne 'https') {
11834: $protocol = 'http';
11835: }
11836: $alldns{$host} = $protocol;
1.869 albertel 11837: }
11838: while (%alldns) {
11839: my ($dns) = keys(%alldns);
1.852 albertel 11840: my $ua=new LWP::UserAgent;
1.1134 raeburn 11841: $ua->timeout(30);
1.979 raeburn 11842: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11843: my $response=$ua->request($request);
1.979 raeburn 11844: delete($alldns{$dns});
1.852 albertel 11845: next if ($response->is_error());
11846: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 11847: unless ($nocache) {
1.1172.2.23 raeburn 11848: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 11849: }
11850: &$func(\@content,$hashref);
1.869 albertel 11851: return;
1.852 albertel 11852: }
11853: close($config);
1.871 albertel 11854: my $which = (split('/',$url))[3];
11855: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11856: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11857: my @content = <$config>;
1.1172.2.17 raeburn 11858: &$func(\@content,$hashref);
11859: return;
11860: }
11861:
11862: # ------------------------------------------------------Get DNS checksums file
11863: sub parse_dns_checksums_tab {
11864: my ($lines,$hashref) = @_;
11865: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11866: my $loncaparev = &get_server_loncaparev($machine_dom);
11867: my ($release,$timestamp) = split(/\-/,$loncaparev);
11868: my (%chksum,%revnum);
11869: if (ref($lines) eq 'ARRAY') {
11870: chomp(@{$lines});
1.1172.2.34 raeburn 11871: my $version = shift(@{$lines});
11872: if ($version eq $release) {
1.1172.2.17 raeburn 11873: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 11874: my ($file,$version,$shasum) = split(/,/,$line);
11875: $chksum{$file} = $shasum;
11876: $revnum{$file} = $version;
1.1172.2.17 raeburn 11877: }
11878: if (ref($hashref) eq 'HASH') {
11879: %{$hashref} = (
11880: sums => \%chksum,
11881: versions => \%revnum,
11882: );
11883: }
11884: }
11885: }
1.869 albertel 11886: return;
1.852 albertel 11887: }
1.1172.2.17 raeburn 11888:
11889: sub fetch_dns_checksums {
11890: my %checksums;
1.1172.2.34 raeburn 11891: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11892: my $loncaparev = &get_server_loncaparev($machine_dom);
11893: my ($release,$timestamp) = split(/\-/,$loncaparev);
11894: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 11895: \%checksums);
11896: return \%checksums;
11897: }
11898:
1.327 albertel 11899: # ------------------------------------------------------------ Read domain file
11900: {
1.852 albertel 11901: my $loaded;
1.846 albertel 11902: my %domain;
11903:
1.852 albertel 11904: sub parse_domain_tab {
11905: my ($lines) = @_;
11906: foreach my $line (@$lines) {
11907: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11908:
1.846 albertel 11909: chomp($line);
1.852 albertel 11910: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11911: my %this_domain;
11912: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11913: 'lang_def', 'city', 'longi', 'lati',
11914: 'primary') {
11915: $this_domain{$field} = shift(@elements);
11916: }
11917: $domain{$name} = \%this_domain;
1.852 albertel 11918: }
11919: }
1.864 albertel 11920:
11921: sub reset_domain_info {
11922: undef($loaded);
11923: undef(%domain);
11924: }
11925:
1.852 albertel 11926: sub load_domain_tab {
1.869 albertel 11927: my ($ignore_cache) = @_;
11928: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11929: my $fh;
11930: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11931: my @lines = <$fh>;
11932: &parse_domain_tab(\@lines);
1.448 albertel 11933: }
1.852 albertel 11934: close($fh);
11935: $loaded = 1;
1.327 albertel 11936: }
1.846 albertel 11937:
11938: sub domain {
1.852 albertel 11939: &load_domain_tab() if (!$loaded);
11940:
1.846 albertel 11941: my ($name,$what) = @_;
11942: return if ( !exists($domain{$name}) );
11943:
11944: if (!$what) {
11945: return $domain{$name}{'description'};
11946: }
11947: return $domain{$name}{$what};
11948: }
1.974 raeburn 11949:
11950: sub domain_info {
11951: &load_domain_tab() if (!$loaded);
11952: return %domain;
11953: }
11954:
1.327 albertel 11955: }
11956:
11957:
1.1 albertel 11958: # ------------------------------------------------------------- Read hosts file
11959: {
1.838 albertel 11960: my %hostname;
1.844 albertel 11961: my %hostdom;
1.845 albertel 11962: my %libserv;
1.852 albertel 11963: my $loaded;
1.888 albertel 11964: my %name_to_host;
1.1074 raeburn 11965: my %internetdom;
1.1107 raeburn 11966: my %LC_dns_serv;
1.852 albertel 11967:
11968: sub parse_hosts_tab {
11969: my ($file) = @_;
11970: foreach my $configline (@$file) {
11971: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11972: chomp($configline);
11973: if ($configline =~ /^\^/) {
11974: if ($configline =~ /^\^([\w.\-]+)/) {
11975: $LC_dns_serv{$1} = 1;
11976: }
11977: next;
11978: }
1.1074 raeburn 11979: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11980: $name=~s/\s//g;
11981: if ($id && $domain && $role && $name) {
11982: $hostname{$id}=$name;
1.888 albertel 11983: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11984: $hostdom{$id}=$domain;
11985: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11986: if (defined($protocol)) {
11987: if ($protocol eq 'https') {
11988: $protocol{$id} = $protocol;
11989: } else {
11990: $protocol{$id} = 'http';
11991: }
1.968 raeburn 11992: } else {
1.969 raeburn 11993: $protocol{$id} = 'http';
1.968 raeburn 11994: }
1.1074 raeburn 11995: if (defined($intdom)) {
11996: $internetdom{$id} = $intdom;
11997: }
1.852 albertel 11998: }
11999: }
12000: }
1.864 albertel 12001:
12002: sub reset_hosts_info {
1.897 albertel 12003: &purge_remembered();
1.864 albertel 12004: &reset_domain_info();
12005: &reset_hosts_ip_info();
1.892 albertel 12006: undef(%name_to_host);
1.864 albertel 12007: undef(%hostname);
12008: undef(%hostdom);
12009: undef(%libserv);
12010: undef($loaded);
12011: }
1.1 albertel 12012:
1.852 albertel 12013: sub load_hosts_tab {
1.869 albertel 12014: my ($ignore_cache) = @_;
12015: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 12016: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12017: my @config = <$config>;
12018: &parse_hosts_tab(\@config);
12019: close($config);
12020: $loaded=1;
1.1 albertel 12021: }
1.852 albertel 12022:
1.838 albertel 12023: sub hostname {
1.852 albertel 12024: &load_hosts_tab() if (!$loaded);
12025:
1.838 albertel 12026: my ($lonid) = @_;
12027: return $hostname{$lonid};
12028: }
1.845 albertel 12029:
1.838 albertel 12030: sub all_hostnames {
1.852 albertel 12031: &load_hosts_tab() if (!$loaded);
12032:
1.838 albertel 12033: return %hostname;
12034: }
1.845 albertel 12035:
1.888 albertel 12036: sub all_names {
12037: &load_hosts_tab() if (!$loaded);
12038:
12039: return %name_to_host;
12040: }
12041:
1.974 raeburn 12042: sub all_host_domain {
12043: &load_hosts_tab() if (!$loaded);
12044: return %hostdom;
12045: }
12046:
1.845 albertel 12047: sub is_library {
1.852 albertel 12048: &load_hosts_tab() if (!$loaded);
12049:
1.845 albertel 12050: return exists($libserv{$_[0]});
12051: }
12052:
12053: sub all_library {
1.852 albertel 12054: &load_hosts_tab() if (!$loaded);
12055:
1.845 albertel 12056: return %libserv;
12057: }
12058:
1.1062 droeschl 12059: sub unique_library {
12060: #2x reverse removes all hostnames that appear more than once
12061: my %unique = reverse &all_library();
12062: return reverse %unique;
12063: }
12064:
1.841 albertel 12065: sub get_servers {
1.852 albertel 12066: &load_hosts_tab() if (!$loaded);
12067:
1.841 albertel 12068: my ($domain,$type) = @_;
12069: my %possible_hosts = ($type eq 'library') ? %libserv
12070: : %hostname;
12071: my %result;
1.842 albertel 12072: if (ref($domain) eq 'ARRAY') {
12073: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12074: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12075: $result{$host} = $hostname;
12076: }
12077: }
12078: } else {
12079: while ( my ($host,$hostname) = each(%possible_hosts)) {
12080: if ($hostdom{$host} eq $domain) {
12081: $result{$host} = $hostname;
12082: }
1.841 albertel 12083: }
12084: }
12085: return %result;
12086: }
1.845 albertel 12087:
1.1062 droeschl 12088: sub get_unique_servers {
12089: my %unique = reverse &get_servers(@_);
12090: return reverse %unique;
12091: }
12092:
1.844 albertel 12093: sub host_domain {
1.852 albertel 12094: &load_hosts_tab() if (!$loaded);
12095:
1.844 albertel 12096: my ($lonid) = @_;
12097: return $hostdom{$lonid};
12098: }
12099:
1.841 albertel 12100: sub all_domains {
1.852 albertel 12101: &load_hosts_tab() if (!$loaded);
12102:
1.841 albertel 12103: my %seen;
12104: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12105: return @uniq;
12106: }
1.1074 raeburn 12107:
12108: sub internet_dom {
12109: &load_hosts_tab() if (!$loaded);
12110:
12111: my ($lonid) = @_;
12112: return $internetdom{$lonid};
12113: }
1.1107 raeburn 12114:
12115: sub is_LC_dns {
12116: &load_hosts_tab() if (!$loaded);
12117:
12118: my ($hostname) = @_;
12119: return exists($LC_dns_serv{$hostname});
12120: }
12121:
1.1 albertel 12122: }
12123:
1.847 albertel 12124: {
12125: my %iphost;
1.856 albertel 12126: my %name_to_ip;
12127: my %lonid_to_ip;
1.869 albertel 12128:
1.847 albertel 12129: sub get_hosts_from_ip {
12130: my ($ip) = @_;
12131: my %iphosts = &get_iphost();
12132: if (ref($iphosts{$ip})) {
12133: return @{$iphosts{$ip}};
12134: }
12135: return;
1.839 albertel 12136: }
1.864 albertel 12137:
12138: sub reset_hosts_ip_info {
12139: undef(%iphost);
12140: undef(%name_to_ip);
12141: undef(%lonid_to_ip);
12142: }
1.856 albertel 12143:
12144: sub get_host_ip {
12145: my ($lonid) = @_;
12146: if (exists($lonid_to_ip{$lonid})) {
12147: return $lonid_to_ip{$lonid};
12148: }
12149: my $name=&hostname($lonid);
12150: my $ip = gethostbyname($name);
12151: return if (!$ip || length($ip) ne 4);
12152: $ip=inet_ntoa($ip);
12153: $name_to_ip{$name} = $ip;
12154: $lonid_to_ip{$lonid} = $ip;
12155: return $ip;
12156: }
1.847 albertel 12157:
12158: sub get_iphost {
1.869 albertel 12159: my ($ignore_cache) = @_;
1.894 albertel 12160:
1.869 albertel 12161: if (!$ignore_cache) {
12162: if (%iphost) {
12163: return %iphost;
12164: }
12165: my ($ip_info,$cached)=
12166: &Apache::lonnet::is_cached_new('iphost','iphost');
12167: if ($cached) {
12168: %iphost = %{$ip_info->[0]};
12169: %name_to_ip = %{$ip_info->[1]};
12170: %lonid_to_ip = %{$ip_info->[2]};
12171: return %iphost;
12172: }
12173: }
1.894 albertel 12174:
12175: # get yesterday's info for fallback
12176: my %old_name_to_ip;
12177: my ($ip_info,$cached)=
12178: &Apache::lonnet::is_cached_new('iphost','iphost');
12179: if ($cached) {
12180: %old_name_to_ip = %{$ip_info->[1]};
12181: }
12182:
1.888 albertel 12183: my %name_to_host = &all_names();
12184: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12185: my $ip;
12186: if (!exists($name_to_ip{$name})) {
12187: $ip = gethostbyname($name);
12188: if (!$ip || length($ip) ne 4) {
1.894 albertel 12189: if (defined($old_name_to_ip{$name})) {
12190: $ip = $old_name_to_ip{$name};
12191: &logthis("Can't find $name defaulting to old $ip");
12192: } else {
12193: &logthis("Name $name no IP found");
12194: next;
12195: }
12196: } else {
12197: $ip=inet_ntoa($ip);
1.847 albertel 12198: }
12199: $name_to_ip{$name} = $ip;
12200: } else {
12201: $ip = $name_to_ip{$name};
1.653 albertel 12202: }
1.888 albertel 12203: foreach my $id (@{ $name_to_host{$name} }) {
12204: $lonid_to_ip{$id} = $ip;
12205: }
12206: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12207: }
1.1172.2.23 raeburn 12208: &do_cache_new('iphost','iphost',
12209: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12210: 48*60*60);
1.869 albertel 12211:
1.847 albertel 12212: return %iphost;
1.598 albertel 12213: }
12214:
1.992 raeburn 12215: #
12216: # Given a DNS returns the loncapa host name for that DNS
12217: #
12218: sub host_from_dns {
12219: my ($dns) = @_;
12220: my @hosts;
12221: my $ip;
12222:
1.993 raeburn 12223: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12224: $ip = $name_to_ip{$dns};
12225: }
12226: if (!$ip) {
12227: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12228: if (length($ip) == 4) {
12229: $ip = &IO::Socket::inet_ntoa($ip);
12230: }
12231: }
12232: if ($ip) {
12233: @hosts = get_hosts_from_ip($ip);
12234: return $hosts[0];
12235: }
12236: return undef;
1.986 foxr 12237: }
1.992 raeburn 12238:
1.1074 raeburn 12239: sub get_internet_names {
12240: my ($lonid) = @_;
12241: return if ($lonid eq '');
12242: my ($idnref,$cached)=
12243: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12244: if ($cached) {
12245: return $idnref;
12246: }
12247: my $ip = &get_host_ip($lonid);
12248: my @hosts = &get_hosts_from_ip($ip);
12249: my %iphost = &get_iphost();
12250: my (@idns,%seen);
12251: foreach my $id (@hosts) {
12252: my $dom = &host_domain($id);
12253: my $prim_id = &domain($dom,'primary');
12254: my $prim_ip = &get_host_ip($prim_id);
12255: next if ($seen{$prim_ip});
12256: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12257: foreach my $id (@{$iphost{$prim_ip}}) {
12258: my $intdom = &internet_dom($id);
12259: unless (grep(/^\Q$intdom\E$/,@idns)) {
12260: push(@idns,$intdom);
12261: }
12262: }
12263: }
12264: $seen{$prim_ip} = 1;
12265: }
1.1172.2.23 raeburn 12266: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12267: }
12268:
1.986 foxr 12269: }
12270:
1.1079 raeburn 12271: sub all_loncaparevs {
1.1172.2.39 raeburn 12272: 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 12273: }
12274:
1.1172.2.27 raeburn 12275: # ------------------------------------------------------- Read loncaparev table
12276: {
12277: sub load_loncaparevs {
12278: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12279: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12280: while (my $configline=<$config>) {
12281: chomp($configline);
12282: my ($hostid,$loncaparev)=split(/:/,$configline);
12283: $loncaparevs{$hostid}=$loncaparev;
12284: }
12285: close($config);
12286: }
12287: }
12288: }
12289: }
12290:
12291: # ----------------------------------------------------- Read serverhostID table
12292: {
12293: sub load_serverhomeIDs {
12294: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12295: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12296: while (my $configline=<$config>) {
12297: chomp($configline);
12298: my ($name,$id)=split(/:/,$configline);
12299: $serverhomeIDs{$name}=$id;
12300: }
12301: close($config);
12302: }
12303: }
12304: }
12305: }
12306:
12307:
1.862 albertel 12308: BEGIN {
12309:
12310: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12311: unless ($readit) {
12312: {
12313: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12314: %perlvar = (%perlvar,%{$configvars});
12315: }
12316:
12317:
1.1 albertel 12318: # ------------------------------------------------------ Read spare server file
12319: {
1.448 albertel 12320: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12321:
12322: while (my $configline=<$config>) {
12323: chomp($configline);
1.284 matthew 12324: if ($configline) {
1.784 albertel 12325: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12326: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12327: push(@{ $spareid{$type} }, $host);
1.1 albertel 12328: }
12329: }
1.448 albertel 12330: close($config);
1.1 albertel 12331: }
1.11 www 12332: # ------------------------------------------------------------ Read permissions
12333: {
1.448 albertel 12334: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12335:
12336: while (my $configline=<$config>) {
1.448 albertel 12337: chomp($configline);
12338: if ($configline) {
12339: my ($role,$perm)=split(/ /,$configline);
12340: if ($perm ne '') { $pr{$role}=$perm; }
12341: }
1.11 www 12342: }
1.448 albertel 12343: close($config);
1.11 www 12344: }
12345:
12346: # -------------------------------------------- Read plain texts for permissions
12347: {
1.448 albertel 12348: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12349:
12350: while (my $configline=<$config>) {
1.448 albertel 12351: chomp($configline);
12352: if ($configline) {
1.742 raeburn 12353: my ($short,@plain)=split(/:/,$configline);
12354: %{$prp{$short}} = ();
12355: if (@plain > 0) {
12356: $prp{$short}{'std'} = $plain[0];
12357: for (my $i=1; $i<@plain; $i++) {
12358: $prp{$short}{'alt'.$i} = $plain[$i];
12359: }
12360: }
1.448 albertel 12361: }
1.135 www 12362: }
1.448 albertel 12363: close($config);
1.135 www 12364: }
12365:
12366: # ---------------------------------------------------------- Read package table
12367: {
1.448 albertel 12368: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12369:
12370: while (my $configline=<$config>) {
1.483 albertel 12371: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12372: chomp($configline);
12373: my ($short,$plain)=split(/:/,$configline);
12374: my ($pack,$name)=split(/\&/,$short);
12375: if ($plain ne '') {
12376: $packagetab{$pack.'&'.$name.'&name'}=$name;
12377: $packagetab{$short}=$plain;
12378: }
1.11 www 12379: }
1.448 albertel 12380: close($config);
1.329 matthew 12381: }
12382:
1.1172.2.27 raeburn 12383: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 12384:
1.1172.2.27 raeburn 12385: &load_loncaparevs();
12386:
12387: # ------------------------------------------------------- Read serverhostID table
12388:
12389: &load_serverhomeIDs();
1.1074 raeburn 12390:
1.1172.2.27 raeburn 12391: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12392: {
12393: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12394: if (-e $file) {
12395: my $parser = HTML::LCParser->new($file);
12396: while (my $token = $parser->get_token()) {
12397: if ($token->[0] eq 'S') {
12398: my $item = $token->[1];
12399: my $name = $token->[2]{'name'};
12400: my $value = $token->[2]{'value'};
12401: if ($item ne '' && $name ne '' && $value ne '') {
12402: my $release = $parser->get_text();
12403: $release =~ s/(^\s*|\s*$ )//gx;
12404: $needsrelease{$item.':'.$name.':'.$value} = $release;
12405: }
12406: }
12407: }
12408: }
1.1073 raeburn 12409: }
12410:
1.1138 raeburn 12411: # ---------------------------------------------------------- Read managers table
12412: {
12413: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12414: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12415: while (my $configline=<$config>) {
12416: chomp($configline);
12417: next if ($configline =~ /^\#/);
12418: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12419: $managerstab{$configline} = 1;
12420: }
12421: }
12422: close($config);
12423: }
12424: }
12425: }
12426:
1.329 matthew 12427: # ------------- set up temporary directory
12428: {
1.1117 foxr 12429: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12430:
1.11 www 12431: }
12432:
1.794 albertel 12433: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12434: 'compress_threshold'=> 20_000,
12435: });
1.185 www 12436:
1.281 www 12437: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12438: $dumpcount=0;
1.958 www 12439: $locknum=0;
1.22 www 12440:
1.163 harris41 12441: &logtouch();
1.672 albertel 12442: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12443: $readit=1;
1.564 albertel 12444: {
12445: use integer;
12446: my $test=(2**32)+1;
1.568 albertel 12447: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12448: &logthis(" Detected 64bit platform ($_64bit)");
12449: }
1.195 www 12450: }
1.1 albertel 12451: }
1.179 www 12452:
1.1 albertel 12453: 1;
1.191 harris41 12454: __END__
12455:
1.243 albertel 12456: =pod
12457:
1.191 harris41 12458: =head1 NAME
12459:
1.243 albertel 12460: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12461:
12462: =head1 SYNOPSIS
12463:
1.243 albertel 12464: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12465:
12466: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12467:
1.243 albertel 12468: Common parameters:
12469:
12470: =over 4
12471:
12472: =item *
12473:
12474: $uname : an internal username (if $cname expecting a course Id specifically)
12475:
12476: =item *
12477:
12478: $udom : a domain (if $cdom expecting a course's domain specifically)
12479:
12480: =item *
12481:
12482: $symb : a resource instance identifier
12483:
12484: =item *
12485:
12486: $namespace : the name of a .db file that contains the data needed or
12487: being set.
12488:
12489: =back
12490:
1.394 bowersj2 12491: =head1 OVERVIEW
1.191 harris41 12492:
1.394 bowersj2 12493: lonnet provides subroutines which interact with the
12494: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12495: about classes, users, and resources.
1.243 albertel 12496:
12497: For many of these objects you can also use this to store data about
12498: them or modify them in various ways.
1.191 harris41 12499:
1.394 bowersj2 12500: =head2 Symbs
1.191 harris41 12501:
1.394 bowersj2 12502: To identify a specific instance of a resource, LON-CAPA uses symbols
12503: or "symbs"X<symb>. These identifiers are built from the URL of the
12504: map, the resource number of the resource in the map, and the URL of
12505: the resource itself. The latter is somewhat redundant, but might help
12506: if maps change.
12507:
12508: An example is
12509:
12510: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12511:
12512: The respective map entry is
12513:
12514: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12515: title="Problem 2">
12516: </resource>
12517:
12518: Symbs are used by the random number generator, as well as to store and
12519: restore data specific to a certain instance of for example a problem.
12520:
12521: =head2 Storing And Retrieving Data
12522:
12523: X<store()>X<cstore()>X<restore()>Three of the most important functions
12524: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12525: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12526: is is the non-critical message twin of cstore. These functions are for
12527: handlers to store a perl hash to a user's permanent data space in an
12528: easy manner, and to retrieve it again on another call. It is expected
12529: that a handler would use this once at the beginning to retrieve data,
12530: and then again once at the end to send only the new data back.
12531:
12532: The data is stored in the user's data directory on the user's
12533: homeserver under the ID of the course.
12534:
12535: The hash that is returned by restore will have all of the previous
12536: value for all of the elements of the hash.
12537:
12538: Example:
12539:
12540: #creating a hash
12541: my %hash;
12542: $hash{'foo'}='bar';
12543:
12544: #storing it
12545: &Apache::lonnet::cstore(\%hash);
12546:
12547: #changing a value
12548: $hash{'foo'}='notbar';
12549:
12550: #adding a new value
12551: $hash{'bar'}='foo';
12552: &Apache::lonnet::cstore(\%hash);
12553:
12554: #retrieving the hash
12555: my %history=&Apache::lonnet::restore();
12556:
12557: #print the hash
12558: foreach my $key (sort(keys(%history))) {
12559: print("\%history{$key} = $history{$key}");
12560: }
12561:
12562: Will print out:
1.191 harris41 12563:
1.394 bowersj2 12564: %history{1:foo} = bar
12565: %history{1:keys} = foo:timestamp
12566: %history{1:timestamp} = 990455579
12567: %history{2:bar} = foo
12568: %history{2:foo} = notbar
12569: %history{2:keys} = foo:bar:timestamp
12570: %history{2:timestamp} = 990455580
12571: %history{bar} = foo
12572: %history{foo} = notbar
12573: %history{timestamp} = 990455580
12574: %history{version} = 2
12575:
12576: Note that the special hash entries C<keys>, C<version> and
12577: C<timestamp> were added to the hash. C<version> will be equal to the
12578: total number of versions of the data that have been stored. The
12579: C<timestamp> attribute will be the UNIX time the hash was
12580: stored. C<keys> is available in every historical section to list which
12581: keys were added or changed at a specific historical revision of a
12582: hash.
12583:
12584: B<Warning>: do not store the hash that restore returns directly. This
12585: will cause a mess since it will restore the historical keys as if the
12586: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12587:
1.394 bowersj2 12588: Calling convention:
1.191 harris41 12589:
1.1172.2.27 raeburn 12590: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12591: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12592:
1.394 bowersj2 12593: For more detailed information, see lonnet specific documentation.
1.191 harris41 12594:
1.394 bowersj2 12595: =head1 RETURN MESSAGES
1.191 harris41 12596:
1.394 bowersj2 12597: =over 4
1.191 harris41 12598:
1.394 bowersj2 12599: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12600:
1.394 bowersj2 12601: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12602: when the connection is brought back up
1.191 harris41 12603:
1.394 bowersj2 12604: =item * B<con_failed>: unable to contact remote host and unable to save message
12605: for later delivery
1.191 harris41 12606:
1.967 bisitz 12607: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12608:
1.394 bowersj2 12609: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12610: that was requested
1.191 harris41 12611:
1.243 albertel 12612: =back
1.191 harris41 12613:
1.243 albertel 12614: =head1 PUBLIC SUBROUTINES
1.191 harris41 12615:
1.243 albertel 12616: =head2 Session Environment Functions
1.191 harris41 12617:
1.243 albertel 12618: =over 4
1.191 harris41 12619:
1.394 bowersj2 12620: =item *
12621: X<appenv()>
1.949 raeburn 12622: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12623: the user envirnoment file, and will be restored for each access this
1.620 albertel 12624: user makes during this session, also modifies the %env for the current
1.949 raeburn 12625: process. Optional rolesarrayref - if defined contains a reference to an array
12626: of roles which are exempt from the restriction on modifying user.role entries
12627: in the user's environment.db and in %env.
1.191 harris41 12628:
12629: =item *
1.394 bowersj2 12630: X<delenv()>
1.987 raeburn 12631: B<delenv($delthis,$regexp)>: removes all items from the session
12632: environment file that begin with $delthis. If the
12633: optional second arg - $regexp - is true, $delthis is treated as a
12634: regular expression, otherwise \Q$delthis\E is used.
12635: The values are also deleted from the current processes %env.
1.191 harris41 12636:
1.795 albertel 12637: =item * get_env_multiple($name)
12638:
12639: gets $name from the %env hash, it seemlessly handles the cases where multiple
12640: values may be defined and end up as an array ref.
12641:
12642: returns an array of values
12643:
1.243 albertel 12644: =back
12645:
12646: =head2 User Information
1.191 harris41 12647:
1.243 albertel 12648: =over 4
1.191 harris41 12649:
12650: =item *
1.394 bowersj2 12651: X<queryauthenticate()>
12652: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12653: authentication scheme
12654:
12655: =item *
1.394 bowersj2 12656: X<authenticate()>
1.1073 raeburn 12657: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12658: authenticate user from domain's lib servers (first use the current
12659: one). C<$upass> should be the users password.
1.1073 raeburn 12660: $checkdefauth is optional (value is 1 if a check should be made to
12661: authenticate user using default authentication method, and allow
12662: account creation if username does not have account in the domain).
12663: $clientcancheckhost is optional (value is 1 if checking whether the
12664: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12665:
12666: =item *
1.394 bowersj2 12667: X<homeserver()>
12668: B<homeserver($uname,$udom)>: find the server which has
12669: the user's directory and files (there must be only one), this caches
12670: the answer, and also caches if there is a borken connection.
1.191 harris41 12671:
12672: =item *
1.394 bowersj2 12673: X<idget()>
12674: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12675: (IDs are a unique resource in a domain, there must be only 1 ID per
12676: username, and only 1 username per ID in a specific domain) (returns
12677: hash: id=>name,id=>name)
1.191 harris41 12678:
12679: =item *
1.394 bowersj2 12680: X<idrget()>
12681: B<idrget($udom,@unames)>: find the IDs behind a list of
12682: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12683:
12684: =item *
1.394 bowersj2 12685: X<idput()>
12686: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12687:
12688: =item *
1.394 bowersj2 12689: X<rolesinit()>
1.1169 droeschl 12690: B<rolesinit($udom,$username)>: get user privileges.
12691: returns user role, first access and timer interval hashes
1.243 albertel 12692:
12693: =item *
1.1171 droeschl 12694: X<privileged()>
12695: B<privileged($username,$domain)>: returns a true if user has a
12696: privileged and active role (i.e. su or dc), false otherwise.
12697:
12698: =item *
1.551 albertel 12699: X<getsection()>
12700: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12701: course $cname, return section name/number or '' for "not in course"
12702: and '-1' for "no section"
12703:
12704: =item *
1.394 bowersj2 12705: X<userenvironment()>
12706: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12707: passed in @what from the requested user's environment, returns a hash
12708:
1.858 raeburn 12709: =item *
12710: X<userlog_query()>
1.859 albertel 12711: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12712: activity.log file. %filters defines filters applied when parsing the
12713: log file. These can be start or end timestamps, or the type of action
12714: - log to look for Login or Logout events, check for Checkin or
12715: Checkout, role for role selection. The response is in the form
12716: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12717: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12718:
1.243 albertel 12719: =back
12720:
12721: =head2 User Roles
12722:
12723: =over 4
12724:
12725: =item *
12726:
1.810 raeburn 12727: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12728: F: full access
12729: U,I,K: authentication modes (cxx only)
12730: '': forbidden
12731: 1: user needs to choose course
12732: 2: browse allowed
1.766 albertel 12733: A: passphrase authentication needed
1.243 albertel 12734:
12735: =item *
12736:
1.1172.2.13 raeburn 12737: constructaccess($url,$setpriv) : check for access to construction space URL
12738:
12739: See if the owner domain and name in the URL match those in the
12740: expected environment. If so, return three element list
12741: ($ownername,$ownerdomain,$ownerhome).
12742:
12743: Otherwise return the null string.
12744:
12745: If second argument 'setpriv' is true, it assigns the privileges,
12746: and returns the same three element list, unless the owner has
12747: blocked "ad hoc" Domain Coordinator access to the Author Space,
12748: in which case the null string is returned.
12749:
12750: =item *
12751:
1.243 albertel 12752: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12753: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12754: and course level
12755:
12756: =item *
12757:
1.988 raeburn 12758: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12759: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12760: $type is Course (default) or Community.
1.988 raeburn 12761: If $forcedefault evaluates to true, text returned will be default
12762: text for $type. Otherwise, if this is a course, the text returned
12763: will be a custom name for the role (if defined in the course's
12764: environment). If no custom name is defined the default is returned.
12765:
1.832 raeburn 12766: =item *
12767:
1.1172.2.23 raeburn 12768: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12769: All arguments are optional. Returns a hash of a roles, either for
12770: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12771: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12772: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12773: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12774: For each key, value is set to colon-separated start and end times for
12775: the role. If no username and domain are specified, will default to
1.934 raeburn 12776: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12777: of role statuses (active, future or previous), roles
12778: (e.g., cc,in, st etc.) and domains of the roles which can be used
12779: to restrict the list of roles reported. If no array ref is
12780: provided for types, will default to return only active roles.
1.834 albertel 12781:
1.1172.2.13 raeburn 12782: =item *
12783:
12784: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12785: user: $uname:$udom has a role in the course: $cdom_$cnum.
12786:
12787: Additional optional arguments are: $type (if role checking is to be restricted
12788: to certain user status types -- previous (expired roles), active (currently
12789: available roles) or future (roles available in the future), and
12790: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 12791: have active Domain Coordinator role in course's domain or in additional
12792: domains (specified in 'Domains to check for privileged users' in course
12793: environment -- set via: Course Settings -> Classlists and staff listing).
12794:
12795: =item *
12796:
12797: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12798: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12799: $possdomains and $possroles are optional array refs -- to domains to check and
12800: roles to check. If $possdomains is not specified, a dump will be done of the
12801: users' roles.db to check for a dc or su role in any domain. This can be
12802: time consuming if &privileged is called repeatedly (e.g., when displaying a
12803: classlist), so in such cases, supplying a $possdomains array is preferred, as
12804: this then allows &privileged_by_domain() to be used, which caches the identity
12805: of privileged users, eliminating the need for repeated calls to &dump().
12806:
12807: =item *
12808:
12809: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12810: where the outer hash keys are domains specified in the $possdomains array ref,
12811: next inner hash keys are privileged roles specified in the $roles array ref,
12812: and the innermost hash contains key = value pairs for username:domain = end:start
12813: for active or future "privileged" users with that role in that domain. To avoid
12814: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12815: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 12816:
1.243 albertel 12817: =back
12818:
12819: =head2 User Modification
12820:
12821: =over 4
12822:
12823: =item *
12824:
1.957 raeburn 12825: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12826: user for the level given by URL. Optional start and end dates (leave empty
12827: string or zero for "no date")
1.191 harris41 12828:
12829: =item *
12830:
1.243 albertel 12831: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12832: change a users, password, possible return values are: ok,
12833: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12834: refused
1.191 harris41 12835:
12836: =item *
12837:
1.243 albertel 12838: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12839:
12840: =item *
12841:
1.1058 raeburn 12842: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12843: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12844:
12845: will update user information (firstname,middlename,lastname,generation,
12846: permanentemail), and if forceid is true, student/employee ID also.
12847: A user's institutional affiliation(s) can also be updated.
12848: User information fields will not be overwritten with empty entries
12849: unless the field is included in the $candelete array reference.
12850: This array is included when a single user is modified via "Manage Users",
12851: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12852:
12853: =item *
12854:
1.286 matthew 12855: modifystudent
12856:
1.957 raeburn 12857: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 12858: The course id is resolved based on the current user's environment.
12859: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12860: associated with a course.
12861:
1.297 matthew 12862: This call is essentially a wrapper for lonnet::modifyuser and
12863: lonnet::modify_student_enrollment
1.286 matthew 12864:
12865: Inputs:
12866:
12867: =over 4
12868:
1.957 raeburn 12869: =item B<$udom> Student's loncapa domain
1.286 matthew 12870:
1.957 raeburn 12871: =item B<$uname> Student's loncapa login name
1.286 matthew 12872:
1.964 bisitz 12873: =item B<$uid> Student/Employee ID
1.286 matthew 12874:
1.957 raeburn 12875: =item B<$umode> Student's authentication mode
1.286 matthew 12876:
1.957 raeburn 12877: =item B<$upass> Student's password
1.286 matthew 12878:
1.957 raeburn 12879: =item B<$first> Student's first name
1.286 matthew 12880:
1.957 raeburn 12881: =item B<$middle> Student's middle name
1.286 matthew 12882:
1.957 raeburn 12883: =item B<$last> Student's last name
1.286 matthew 12884:
1.957 raeburn 12885: =item B<$gene> Student's generation
1.286 matthew 12886:
1.957 raeburn 12887: =item B<$usec> Student's section in course
1.286 matthew 12888:
12889: =item B<$end> Unix time of the roles expiration
12890:
12891: =item B<$start> Unix time of the roles start date
12892:
12893: =item B<$forceid> If defined, allow $uid to be changed
12894:
12895: =item B<$desiredhome> server to use as home server for student
12896:
1.957 raeburn 12897: =item B<$email> Student's permanent e-mail address
12898:
12899: =item B<$type> Type of enrollment (auto or manual)
12900:
1.963 raeburn 12901: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12902:
12903: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12904:
1.963 raeburn 12905: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12906:
1.963 raeburn 12907: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12908:
1.1172.2.19 raeburn 12909: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12910:
12911: =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 12912:
1.286 matthew 12913: =back
1.297 matthew 12914:
12915: =item *
12916:
12917: modify_student_enrollment
12918:
1.1172.2.31 raeburn 12919: Change a student's enrollment status in a class. The environment variable
1.297 matthew 12920: 'role.request.course' must be defined for this function to proceed.
12921:
12922: Inputs:
12923:
12924: =over 4
12925:
1.1172.2.31 raeburn 12926: =item $udom, student's domain
1.297 matthew 12927:
1.1172.2.31 raeburn 12928: =item $uname, student's name
1.297 matthew 12929:
1.1172.2.31 raeburn 12930: =item $uid, student's user id
1.297 matthew 12931:
1.1172.2.31 raeburn 12932: =item $first, student's first name
1.297 matthew 12933:
12934: =item $middle
12935:
12936: =item $last
12937:
12938: =item $gene
12939:
12940: =item $usec
12941:
12942: =item $end
12943:
12944: =item $start
12945:
1.957 raeburn 12946: =item $type
12947:
12948: =item $locktype
12949:
12950: =item $cid
12951:
12952: =item $selfenroll
12953:
12954: =item $context
12955:
1.1172.2.19 raeburn 12956: =item $credits, number of credits student will earn from this class
12957:
1.297 matthew 12958: =back
12959:
1.191 harris41 12960:
12961: =item *
12962:
1.243 albertel 12963: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12964: custom role; give a custom role to a user for the level given by URL. Specify
12965: name and domain of role author, and role name
1.191 harris41 12966:
12967: =item *
12968:
1.243 albertel 12969: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12970:
12971: =item *
12972:
1.243 albertel 12973: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12974:
12975: =back
12976:
12977: =head2 Course Infomation
12978:
12979: =over 4
1.191 harris41 12980:
12981: =item *
12982:
1.1118 foxr 12983: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12984: specified course id, including all environment settings for the
12985: course, the description of the course will be in the hash under the
12986: key 'description'
1.191 harris41 12987:
1.1118 foxr 12988: $options is an optional parameter that if supplied is a hash reference that controls
12989: what how this function works. It has the following key/values:
12990:
12991: =over 4
12992:
12993: =item freshen_cache
12994:
12995: If defined, and the environment cache for the course is valid, it is
12996: returned in the returned hash.
12997:
12998: =item one_time
12999:
13000: If defined, the last cache time is set to _now_
13001:
13002: =item user
13003:
13004: If defined, the supplied username is used instead of the current user.
13005:
13006:
13007: =back
13008:
1.191 harris41 13009: =item *
13010:
1.624 albertel 13011: resdata($name,$domain,$type,@which) : request for current parameter
13012: setting for a specific $type, where $type is either 'course' or 'user',
13013: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 13014: answers for 10 minutes.
1.243 albertel 13015:
1.877 foxr 13016: =item *
13017:
13018: get_courseresdata($courseid, $domain) : dump the entire course resource
13019: data base, returning a hash that is keyed by the resource name and has
13020: values that are the resource value. I believe that the timestamps and
13021: versions are also returned.
13022:
1.1172.2.31 raeburn 13023: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13024: supplemental content area. This routine caches the number of files for
13025: 10 minutes.
13026:
1.243 albertel 13027: =back
13028:
13029: =head2 Course Modification
13030:
13031: =over 4
1.191 harris41 13032:
13033: =item *
13034:
1.243 albertel 13035: writecoursepref($courseid,%prefs) : write preferences (environment
13036: database) for a course
1.191 harris41 13037:
13038: =item *
13039:
1.1011 raeburn 13040: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13041:
13042: =item *
13043:
1.1038 raeburn 13044: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13045:
1.1167 droeschl 13046: =item *
13047:
13048: is_course($courseid), is_course($cdom, $cnum)
13049:
13050: Accepts either a combined $courseid (in the form of domain_courseid) or the
13051: two component version $cdom, $cnum. It checks if the specified course exists.
13052:
13053: Returns:
13054: undef if the course doesn't exist, otherwise
13055: in scalar context the combined courseid.
13056: in list context the two components of the course identifier, domain and
13057: courseid.
13058:
1.243 albertel 13059: =back
13060:
13061: =head2 Resource Subroutines
13062:
13063: =over 4
1.191 harris41 13064:
13065: =item *
13066:
1.243 albertel 13067: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13068:
13069: =item *
13070:
1.243 albertel 13071: repcopy($filename) : subscribes to the requested file, and attempts to
13072: replicate from the owning library server, Might return
1.607 raeburn 13073: 'unavailable', 'not_found', 'forbidden', 'ok', or
13074: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13075: resource. Expects the local filesystem pathname
13076: (/home/httpd/html/res/....)
13077:
13078: =back
13079:
13080: =head2 Resource Information
13081:
13082: =over 4
1.191 harris41 13083:
13084: =item *
13085:
1.1172.2.28 raeburn 13086: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13087: and returns the value of a variety of different possible values,
13088: $varname should be a request string, and the other parameters can be
13089: used to specify who and what one is asking about. Ordinarily, $cid
13090: does not need to be specified, as it is retrived from
13091: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13092: within lonuserstate::loadmap() when initializing a course, before
13093: $env{'request.course.id'} has been set, so it needs to be provided
13094: in that one case.
1.243 albertel 13095:
13096: Possible values for $varname are environment.lastname (or other item
13097: from the envirnment hash), user.name (or someother aspect about the
13098: user), resource.0.maxtries (or some other part and parameter of a
13099: resource)
1.204 albertel 13100:
13101: =item *
13102:
1.243 albertel 13103: directcondval($number) : get current value of a condition; reads from a state
13104: string
1.204 albertel 13105:
13106: =item *
13107:
1.243 albertel 13108: condval($condidx) : value of condition index based on state
1.204 albertel 13109:
13110: =item *
13111:
1.243 albertel 13112: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13113: resource's metadata, $what should be either a specific key, or either
13114: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13115: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13116:
13117: this function automatically caches all requests
1.191 harris41 13118:
13119: =item *
13120:
1.243 albertel 13121: metadata_query($query,$custom,$customshow) : make a metadata query against the
13122: network of library servers; returns file handle of where SQL and regex results
13123: will be stored for query
1.191 harris41 13124:
13125: =item *
13126:
1.243 albertel 13127: symbread($filename) : return symbolic list entry (filename argument optional);
13128: returns the data handle
1.191 harris41 13129:
13130: =item *
13131:
1.1172.2.17 raeburn 13132: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 13133: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13134: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 13135: on failure, user must be in a course, as it assumes the existence of
13136: the course initial hash, and uses $env('request.course.id'}. The third
13137: arg is an optional reference to a scalar. If this arg is passed in the
13138: call to symbverify, it will be set to 1 if the symb has been set to be
13139: encrypted; otherwise it will be null.
1.243 albertel 13140:
1.191 harris41 13141: =item *
13142:
1.243 albertel 13143: symbclean($symb) : removes versions numbers from a symb, returns the
13144: cleaned symb
1.191 harris41 13145:
13146: =item *
13147:
1.243 albertel 13148: is_on_map($uri) : checks if the $uri is somewhere on the current
13149: course map, user must be in a course for it to work.
1.191 harris41 13150:
13151: =item *
13152:
1.243 albertel 13153: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13154:
13155: =item *
13156:
1.243 albertel 13157: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13158: a random seed, all arguments are optional, if they aren't sent it uses the
13159: environment to derive them. Note: if symb isn't sent and it can't get one
13160: from &symbread it will use the current time as its return value
1.191 harris41 13161:
13162: =item *
13163:
1.243 albertel 13164: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13165: unfakeable, receipt
1.191 harris41 13166:
13167: =item *
13168:
1.620 albertel 13169: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13170:
13171: =item *
13172:
1.243 albertel 13173: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13174:
13175: =item *
13176:
1.243 albertel 13177: 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 13178:
13179: =item *
13180:
1.243 albertel 13181: 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 13182:
13183: =item *
13184:
1.243 albertel 13185: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13186:
13187: =item *
13188:
1.243 albertel 13189: devalidate($symb) : devalidate temporary spreadsheet calculations,
13190: forcing spreadsheet to reevaluate the resource scores next time.
13191:
1.1172.2.13 raeburn 13192: =item *
13193:
13194: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13195: when viewing in course context.
13196:
13197: input: six args -- filename (decluttered), course number, course domain,
13198: url, symb (if registered) and group (if this is a
13199: group item -- e.g., bulletin board, group page etc.).
13200:
13201: output: array of five scalars --
13202: $cfile -- url for file editing if editable on current server
13203: $home -- homeserver of resource (i.e., for author if published,
13204: or course if uploaded.).
13205: $switchserver -- 1 if server switch will be needed.
13206: $forceedit -- 1 if icon/link should be to go to edit mode
13207: $forceview -- 1 if icon/link should be to go to view mode
13208:
13209: =item *
13210:
13211: is_course_upload($file,$cnum,$cdom)
13212:
13213: Used in course context to determine if current file was uploaded to
13214: the course (i.e., would be found in /userfiles/docs on the course's
13215: homeserver.
13216:
13217: input: 3 args -- filename (decluttered), course number and course domain.
13218: output: boolean -- 1 if file was uploaded.
13219:
1.243 albertel 13220: =back
13221:
13222: =head2 Storing/Retreiving Data
13223:
13224: =over 4
1.191 harris41 13225:
13226: =item *
13227:
1.243 albertel 13228: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13229: for this url; hashref needs to be given and should be a \%hashname; the
13230: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13231: be derived from the env
1.191 harris41 13232:
13233: =item *
13234:
1.243 albertel 13235: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13236: uses critical subroutine
1.191 harris41 13237:
13238: =item *
13239:
1.243 albertel 13240: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13241: all args are optional
1.191 harris41 13242:
13243: =item *
13244:
1.717 albertel 13245: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13246: dumps the complete (or key matching regexp) namespace into a hash
13247: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13248: normally &store()ed into
13249:
13250: $range should be either an integer '100' (give me the first 100
13251: matching records)
13252: or be two integers sperated by a - with no spaces
13253: '30-50' (give me the 30th through the 50th matching
13254: records)
13255:
13256:
13257: =item *
13258:
13259: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13260: replaces a &store() version of data with a replacement set of data
13261: for a particular resource in a namespace passed in the $storehash hash
13262: reference
13263:
13264: =item *
13265:
1.243 albertel 13266: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13267: works very similar to store/cstore, but all data is stored in a
13268: temporary location and can be reset using tmpreset, $storehash should
13269: be a hash reference, returns nothing on success
1.191 harris41 13270:
13271: =item *
13272:
1.243 albertel 13273: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13274: similar to restore, but all data is stored in a temporary location and
13275: can be reset using tmpreset. Returns a hash of values on success,
13276: error string otherwise.
1.191 harris41 13277:
13278: =item *
13279:
1.243 albertel 13280: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13281: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13282:
13283: =item *
13284:
1.243 albertel 13285: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13286: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13287:
13288: =item *
13289:
1.243 albertel 13290: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13291: namesp ($udom and $uname are optional)
1.191 harris41 13292:
13293: =item *
13294:
1.702 albertel 13295: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13296: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13297: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13298:
1.702 albertel 13299: $range should be either an integer '100' (give me the first 100
13300: matching records)
13301: or be two integers sperated by a - with no spaces
13302: '30-50' (give me the 30th through the 50th matching
13303: records)
1.449 matthew 13304: =item *
13305:
13306: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13307: $store can be a scalar, an array reference, or if the amount to be
13308: incremented is > 1, a hash reference.
13309:
13310: ($udom and $uname are optional)
1.191 harris41 13311:
13312: =item *
13313:
1.243 albertel 13314: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13315: ($udom and $uname are optional)
1.191 harris41 13316:
13317: =item *
13318:
1.243 albertel 13319: cput($namespace,$storehash,$udom,$uname) : critical put
13320: ($udom and $uname are optional)
1.191 harris41 13321:
13322: =item *
13323:
1.748 albertel 13324: newput($namespace,$storehash,$udom,$uname) :
13325:
13326: Attempts to store the items in the $storehash, but only if they don't
13327: currently exist, if this succeeds you can be certain that you have
13328: successfully created a new key value pair in the $namespace db.
13329:
13330:
13331: Args:
13332: $namespace: name of database to store values to
13333: $storehash: hashref to store to the db
13334: $udom: (optional) domain of user containing the db
13335: $uname: (optional) name of user caontaining the db
13336:
13337: Returns:
13338: 'ok' -> succeeded in storing all keys of $storehash
13339: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13340: least <key> already existed in the db (other
13341: requested keys may also already exist)
1.967 bisitz 13342: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13343: 'con_lost' -> unable to contact request server
13344: 'refused' -> action was not allowed by remote machine
13345:
13346:
13347: =item *
13348:
1.243 albertel 13349: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13350: reference filled in from namesp (encrypts the return communication)
13351: ($udom and $uname are optional)
1.191 harris41 13352:
13353: =item *
13354:
1.243 albertel 13355: log($udom,$name,$home,$message) : write to permanent log for user; use
13356: critical subroutine
13357:
1.806 raeburn 13358: =item *
13359:
1.860 raeburn 13360: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13361: array reference filled in from namespace found in domain level on either
13362: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13363:
13364: =item *
13365:
1.860 raeburn 13366: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13367: domain level either on specified domain server ($uhome) or primary domain
13368: server ($udom and $uhome are optional)
1.806 raeburn 13369:
1.943 raeburn 13370: =item *
13371:
1.1172.2.35 raeburn 13372: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13373: for: authentication, language, quotas, timezone, date locale, and portal URL in
13374: the target domain.
13375:
13376: May also include additional key => value pairs for the following groups:
13377:
13378: =over
13379:
13380: =item
13381: disk quotas (MB allocated by default to portfolios and authoring spaces).
13382:
13383: =over
13384:
13385: =item defaultquota, authorquota
13386:
13387: =back
13388:
13389: =item
13390: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13391: portfolio for users).
13392:
13393: =over
13394:
13395: =item
13396: aboutme, blog, webdav, portfolio
13397:
13398: =back
13399:
13400: =item
13401: requestcourses: ability to request courses, and how requests are processed.
13402:
13403: =over
13404:
13405: =item
1.1172.2.37 raeburn 13406: official, unofficial, community, textbook
1.1172.2.35 raeburn 13407:
13408: =back
13409:
13410: =item
13411: inststatus: types of institutional affiliation, and order in which they are displayed.
13412:
13413: =over
13414:
13415: =item
1.1172.2.44! raeburn 13416: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 13417:
13418: =back
13419:
13420: =item
13421: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13422: for course's uploaded content.
13423:
13424: =over
13425:
13426: =item
1.1172.2.37 raeburn 13427: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, communityquota, textbookquota
1.1172.2.35 raeburn 13428:
13429: =back
13430:
13431: =item
13432: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13433: on your servers.
13434:
13435: =over
13436:
13437: =item
13438: remotesessions, hostedsessions
13439:
13440: =back
13441:
13442: =back
13443:
13444: In cases where a domain coordinator has never used the "Set Domain Configuration"
13445: utility to create a configuration.db file on a domain's primary library server
13446: only the following domain defaults: auth_def, auth_arg_def, lang_def
13447: -- corresponding values are authentication type (internal, krb4, krb5,
13448: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13449: will be available. Values are retrieved from cache (if current), unless the
13450: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13451: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13452:
13453: Typical usage:
1.943 raeburn 13454:
1.1172.2.35 raeburn 13455: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13456:
1.243 albertel 13457: =back
13458:
13459: =head2 Network Status Functions
13460:
13461: =over 4
1.191 harris41 13462:
13463: =item *
13464:
1.1137 raeburn 13465: dirlist() : return directory list based on URI (first arg).
13466:
13467: Inputs: 1 required, 5 optional.
13468:
13469: =over
13470:
13471: =item
13472: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13473:
13474: =item
13475: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13476:
13477: =item
13478: $username - username of user/course to be listed. Extracted from $uri if absent.
13479:
13480: =item
13481: $getpropath - boolean: 1 if prepend path using &propath().
13482:
13483: =item
13484: $getuserdir - boolean: 1 if prepend path for "userfiles".
13485:
13486: =item
13487: $alternateRoot - path to prepend in place of path from $uri.
13488:
13489: =back
13490:
13491: Returns: Array of up to two items.
13492:
13493: =over
13494:
13495: a reference to an array of files/subdirectories
13496:
13497: =over
13498:
13499: Each element in the array of files/subdirectories is a & separated list of
13500: item name and the result of running stat on the item. If dirlist was requested
13501: for a file instead of a directory, the item name will be ''. For a directory
13502: listing, if the item is a metadata file, the element will end &N&M
13503: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13504: default copyright set (1).
13505:
13506: =back
13507:
13508: a scalar containing error condition (if encountered).
13509:
13510: =over
13511:
13512: =item
13513: no_host (no homeserver identified for $username:$domain).
13514:
13515: =item
13516: no_such_host (server contacted for listing not identified as valid host).
13517:
13518: =item
13519: con_lost (connection to remote server failed).
13520:
13521: =item
13522: refused (invalid $username:$domain received on lond side).
13523:
13524: =item
13525: no_such_dir (directory at specified path on lond side does not exist).
13526:
13527: =item
13528: empty (directory at specified path on lond side is empty).
13529:
13530: =over
13531:
13532: This is currently not encountered because the &ls3, &ls2,
13533: &ls (_handler) routines on the lond side do not filter out
13534: . and .. from a directory listing.
13535:
13536: =back
13537:
13538: =back
13539:
13540: =back
1.191 harris41 13541:
13542: =item *
13543:
1.243 albertel 13544: spareserver() : find server with least workload from spare.tab
13545:
1.986 foxr 13546:
13547: =item *
13548:
13549: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13550: if there is no corresponding loncapa host.
13551:
1.243 albertel 13552: =back
13553:
1.986 foxr 13554:
1.243 albertel 13555: =head2 Apache Request
13556:
13557: =over 4
1.191 harris41 13558:
13559: =item *
13560:
1.243 albertel 13561: ssi($url,%hash) : server side include, does a complete request cycle on url to
13562: localhost, posts hash
13563:
13564: =back
13565:
13566: =head2 Data to String to Data
13567:
13568: =over 4
1.191 harris41 13569:
13570: =item *
13571:
1.243 albertel 13572: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13573: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13574:
13575: =item *
13576:
1.243 albertel 13577: hashref2str($hashref) : convert a hashref into a string complete with
13578: escaping and '=' and '&' separators, supports elements that are
13579: arrayrefs and hashrefs
1.191 harris41 13580:
13581: =item *
13582:
1.243 albertel 13583: arrayref2str($arrayref) : convert an arrayref into a string complete
13584: with escaping and '&' separators, supports elements that are arrayrefs
13585: and hashrefs
1.191 harris41 13586:
13587: =item *
13588:
1.243 albertel 13589: str2hash($string) : convert string to hash using unescaping and
13590: splitting on '=' and '&', supports elements that are arrayrefs and
13591: hashrefs
1.191 harris41 13592:
13593: =item *
13594:
1.243 albertel 13595: str2array($string) : convert string to hash using unescaping and
13596: splitting on '&', supports elements that are arrayrefs and hashrefs
13597:
13598: =back
13599:
13600: =head2 Logging Routines
13601:
13602:
13603: These routines allow one to make log messages in the lonnet.log and
13604: lonnet.perm logfiles.
1.191 harris41 13605:
1.1119 foxr 13606: =over 4
13607:
1.191 harris41 13608: =item *
13609:
1.243 albertel 13610: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13611:
13612: =item *
13613:
1.243 albertel 13614: logthis() : append message to the normal lonnet.log file, it gets
13615: preiodically rolled over and deleted.
1.191 harris41 13616:
13617: =item *
13618:
1.243 albertel 13619: logperm() : append a permanent message to lonnet.perm.log, this log
13620: file never gets deleted by any automated portion of the system, only
13621: messages of critical importance should go in here.
13622:
1.1119 foxr 13623:
1.243 albertel 13624: =back
13625:
13626: =head2 General File Helper Routines
13627:
13628: =over 4
1.191 harris41 13629:
13630: =item *
13631:
1.481 raeburn 13632: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13633: (a) files in /uploaded
13634: (i) If a local copy of the file exists -
13635: compares modification date of local copy with last-modified date for
13636: definitive version stored on home server for course. If local copy is
13637: stale, requests a new version from the home server and stores it.
13638: If the original has been removed from the home server, then local copy
13639: is unlinked.
13640: (ii) If local copy does not exist -
13641: requests the file from the home server and stores it.
13642:
13643: If $caller is 'uploadrep':
13644: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13645: for request for files originally uploaded via DOCS.
13646: - returns 'ok' if fresh local copy now available, -1 otherwise.
13647:
13648: Otherwise:
13649: This indicates a call from the content generation phase of the request.
13650: - returns the entire contents of the file or -1.
13651:
13652: (b) files in /res
13653: - returns the entire contents of a file or -1;
13654: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13655:
1.712 albertel 13656:
13657: =item *
13658:
13659: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13660: reference
13661:
13662: returns either a stat() list of data about the file or an empty list
13663: if the file doesn't exist or couldn't find out about it (connection
13664: problems or user unknown)
13665:
1.191 harris41 13666: =item *
13667:
1.243 albertel 13668: filelocation($dir,$file) : returns file system location of a file
13669: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13670: directory that relative $file lookups are to looked in ($dir of /a/dir
13671: and a file of ../bob will become /a/bob)
1.191 harris41 13672:
13673: =item *
13674:
13675: hreflocation($dir,$file) : returns file system location or a URL; same as
13676: filelocation except for hrefs
13677:
13678: =item *
13679:
13680: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13681:
1.243 albertel 13682: =back
13683:
1.608 albertel 13684: =head2 Usererfile file routines (/uploaded*)
13685:
13686: =over 4
13687:
13688: =item *
13689:
13690: userfileupload(): main rotine for putting a file in a user or course's
13691: filespace, arguments are,
13692:
1.620 albertel 13693: formname - required - this is the name of the element in $env where the
1.608 albertel 13694: filename, and the contents of the file to create/modifed exist
1.620 albertel 13695: the filename is in $env{'form.'.$formname.'.filename'} and the
13696: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13697: context - if coursedoc, store the file in the course of the active role
13698: of the current user;
13699: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13700: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13701: subdir - required - subdirectory to put the file in under ../userfiles/
13702: if undefined, it will be placed in "unknown"
13703:
13704: (This routine calls clean_filename() to remove any dangerous
13705: characters from the filename, and then calls finuserfileupload() to
13706: complete the transaction)
13707:
13708: returns either the url of the uploaded file (/uploaded/....) if successful
13709: and /adm/notfound.html if unsuccessful
13710:
13711: =item *
13712:
13713: clean_filename(): routine for cleaing a filename up for storage in
13714: userfile space, argument is:
13715:
13716: filename - proposed filename
13717:
13718: returns: the new clean filename
13719:
13720: =item *
13721:
1.1090 raeburn 13722: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13723: userspace, probably shouldn't be called directly
13724:
13725: docuname: username or courseid of destination for the file
13726: docudom: domain of user/course of destination for the file
13727: formname: same as for userfileupload()
1.1090 raeburn 13728: fname: filename (including subdirectories) for the file
13729: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13730: allfiles: reference to hash used to store objects found by parser
13731: codebase: reference to hash used for codebases of java objects found by parser
13732: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13733: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13734: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13735: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13736: context: if 'overwrite', will move the uploaded file from its temporary location to
13737: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13738: mimetype: reference to scalar to accommodate mime type determined
13739: from File::MMagic if $parser = parse.
1.608 albertel 13740:
13741: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13742: and /adm/notfound.html if unsuccessful (or an error message if context
13743: was 'overwrite').
13744:
1.608 albertel 13745:
13746: =item *
13747:
13748: renameuserfile(): renames an existing userfile to a new name
13749:
13750: Args:
13751: docuname: username or courseid of destination for the file
13752: docudom: domain of user/course of destination for the file
13753: old: current file name (including any subdirs under userfiles)
13754: new: desired file name (including any subdirs under userfiles)
13755:
13756: =item *
13757:
13758: mkdiruserfile(): creates a directory is a userfiles dir
13759:
13760: Args:
13761: docuname: username or courseid of destination for the file
13762: docudom: domain of user/course of destination for the file
13763: dir: dir to create (including any subdirs under userfiles)
13764:
13765: =item *
13766:
13767: removeuserfile(): removes a file that exists in userfiles
13768:
13769: Args:
13770: docuname: username or courseid of destination for the file
13771: docudom: domain of user/course of destination for the file
13772: fname: filname to delete (including any subdirs under userfiles)
13773:
13774: =item *
13775:
13776: removeuploadedurl(): convience function for removeuserfile()
13777:
13778: Args:
13779: url: a full /uploaded/... url to delete
13780:
1.747 albertel 13781: =item *
13782:
13783: get_portfile_permissions():
13784: Args:
13785: domain: domain of user or course contain the portfolio files
13786: user: name of user or num of course contain the portfolio files
13787: Returns:
13788: hashref of a dump of the proper file_permissions.db
13789:
13790:
13791: =item *
13792:
13793: get_access_controls():
13794:
13795: Args:
13796: current_permissions: the hash ref returned from get_portfile_permissions()
13797: group: (optional) the group you want the files associated with
13798: file: (optional) the file you want access info on
13799:
13800: Returns:
1.749 raeburn 13801: a hash (keys are file names) of hashes containing
13802: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13803: values are XML containing access control settings (see below)
1.747 albertel 13804:
13805: Internal notes:
13806:
1.749 raeburn 13807: access controls are stored in file_permissions.db as key=value pairs.
13808: key -> path to file/file_name\0uniqueID:scope_end_start
13809: where scope -> public,guest,course,group,domains or users.
13810: end -> UNIX time for end of access (0 -> no end date)
13811: start -> UNIX time for start of access
13812:
13813: value -> XML description of access control
13814: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13815: <start></start>
13816: <end></end>
13817:
13818: <password></password> for scope type = guest
13819:
13820: <domain></domain> for scope type = course or group
13821: <number></number>
13822: <roles id="">
13823: <role></role>
13824: <access></access>
13825: <section></section>
13826: <group></group>
13827: </roles>
13828:
13829: <dom></dom> for scope type = domains
13830:
13831: <users> for scope type = users
13832: <user>
13833: <uname></uname>
13834: <udom></udom>
13835: </user>
13836: </users>
13837: </scope>
13838:
13839: Access data is also aggregated for each file in an additional key=value pair:
13840: key -> path to file/file_name\0accesscontrol
13841: value -> reference to hash
13842: hash contains key = value pairs
13843: where key = uniqueID:scope_end_start
13844: value = UNIX time record was last updated
13845:
13846: Used to improve speed of look-ups of access controls for each file.
13847:
13848: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13849:
1.1172.2.13 raeburn 13850: =item *
13851:
1.749 raeburn 13852: modify_access_controls():
13853:
13854: Modifies access controls for a portfolio file
13855: Args
13856: 1. file name
13857: 2. reference to hash of required changes,
13858: 3. domain
13859: 4. username
13860: where domain,username are the domain of the portfolio owner
13861: (either a user or a course)
13862:
13863: Returns:
13864: 1. result of additions or updates ('ok' or 'error', with error message).
13865: 2. result of deletions ('ok' or 'error', with error message).
13866: 3. reference to hash of any new or updated access controls.
13867: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13868: key = integer (inbound ID)
1.1172.2.13 raeburn 13869: value = uniqueID
13870:
13871: =item *
13872:
13873: get_timebased_id():
13874:
13875: Attempts to get a unique timestamp-based suffix for use with items added to a
13876: course via the Course Editor (e.g., folders, composite pages,
13877: group bulletin boards).
13878:
13879: Args: (first three required; six others optional)
13880:
13881: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13882: docssequence, or name of group
13883:
13884: 2. keyid (alphanumeric): name of temporary locking key in hash,
13885: e.g., num, boardids
13886:
13887: 3. namespace: name of gdbm file used to store suffixes already assigned;
13888: file will be named nohist_namespace.db
13889:
13890: 4. cdom: domain of course; default is current course domain from %env
13891:
13892: 5. cnum: course number; default is current course number from %env
13893:
13894: 6. idtype: set to concat if an additional digit is to be appended to the
13895: unix timestamp to form the suffix, if the plain timestamp is already
13896: in use. Default is to not do this, but simply increment the unix
13897: timestamp by 1 until a unique key is obtained.
13898:
13899: 7. who: holder of locking key; defaults to user:domain for user.
13900:
13901: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13902: retrying); default is 3.
13903:
13904: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13905:
13906: Returns:
13907:
13908: 1. suffix obtained (numeric)
13909:
13910: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13911:
13912: 3. error: contains (localized) error message if an error occurred.
13913:
1.747 albertel 13914:
1.608 albertel 13915: =back
13916:
1.243 albertel 13917: =head2 HTTP Helper Routines
13918:
13919: =over 4
13920:
1.191 harris41 13921: =item *
13922:
13923: escape() : unpack non-word characters into CGI-compatible hex codes
13924:
13925: =item *
13926:
13927: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13928:
1.243 albertel 13929: =back
13930:
13931: =head1 PRIVATE SUBROUTINES
13932:
13933: =head2 Underlying communication routines (Shouldn't call)
13934:
13935: =over 4
13936:
13937: =item *
13938:
13939: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13940:
13941: =item *
13942:
13943: reply() : uses subreply to send a message to remote machine, logs all failures
13944:
13945: =item *
13946:
13947: critical() : passes a critical message to another server; if cannot
13948: get through then place message in connection buffer directory and
13949: returns con_delayed, if incapable of saving message, returns
13950: con_failed
13951:
13952: =item *
13953:
13954: reconlonc() : tries to reconnect lonc client processes.
13955:
13956: =back
13957:
13958: =head2 Resource Access Logging
13959:
13960: =over 4
13961:
13962: =item *
13963:
13964: flushcourselogs() : flush (save) buffer logs and access logs
13965:
13966: =item *
13967:
13968: courselog($what) : save message for course in hash
13969:
13970: =item *
13971:
13972: courseacclog($what) : save message for course using &courselog(). Perform
13973: special processing for specific resource types (problems, exams, quizzes, etc).
13974:
1.191 harris41 13975: =item *
13976:
13977: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13978: as a PerlChildExitHandler
1.243 albertel 13979:
13980: =back
13981:
13982: =head2 Other
13983:
13984: =over 4
13985:
13986: =item *
13987:
13988: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 13989:
13990: =back
13991:
13992: =cut
1.877 foxr 13993:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>