Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.40
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.40! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.39 2014/01/05 11:45:01 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 {
888: my ($try_server, $spare_server, $lowest_load) = @_;
889:
890: my $loadans = &reply('load', $try_server);
891: my $userloadans = &reply('userload',$try_server);
892:
893: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 894: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 895: }
896:
897: my $load;
898: if ($loadans =~ /\d/) {
899: if ($userloadans =~ /\d/) {
900: #both are numbers, pick the bigger one
901: $load = ($loadans > $userloadans) ? $loadans
902: : $userloadans;
1.411 albertel 903: } else {
1.784 albertel 904: $load = $loadans;
1.411 albertel 905: }
1.784 albertel 906: } else {
907: $load = $userloadans;
908: }
909:
910: if (($load =~ /\d/) && ($load < $lowest_load)) {
911: $spare_server = $try_server;
912: $lowest_load = $load;
1.370 albertel 913: }
1.784 albertel 914: return ($spare_server,$lowest_load);
1.202 matthew 915: }
1.914 albertel 916:
917: # --------------------------- ask offload servers if user already has a session
918: sub find_existing_session {
919: my ($udom,$uname) = @_;
1.1123 raeburn 920: my $spareshash = &this_host_spares($udom);
921: if (ref($spareshash) eq 'HASH') {
922: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
923: foreach my $try_server (@{ $spareshash->{'primary'} }) {
924: return $try_server if (&has_user_session($try_server, $udom, $uname));
925: }
926: }
927: if (ref($spareshash->{'default'}) eq 'ARRAY') {
928: foreach my $try_server (@{ $spareshash->{'default'} }) {
929: return $try_server if (&has_user_session($try_server, $udom, $uname));
930: }
931: }
1.914 albertel 932: }
933: return;
934: }
935:
936: # -------------------------------- ask if server already has a session for user
937: sub has_user_session {
938: my ($lonid,$udom,$uname) = @_;
939: my $result = &reply(join(':','userhassession',
940: map {&escape($_)} ($udom,$uname)),$lonid);
941: return 1 if ($result eq 'ok');
942:
943: return 0;
944: }
945:
1.1076 raeburn 946: # --------- determine least loaded server in a user's domain which allows login
947:
948: sub choose_server {
1.1115 raeburn 949: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 950: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 951: my %servers = &get_servers($udom);
1.1076 raeburn 952: my $lowest_load = 30000;
1.1151 raeburn 953: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 954: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 955: my $loginvia;
956: if ($checkloginvia) {
957: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 958: if ($loginvia) {
959: my ($server,$path) = split(/:/,$loginvia);
960: ($login_host, $lowest_load) =
961: &compare_server_load($server, $login_host, $lowest_load);
962: if ($login_host eq $server) {
963: $portal_path = $path;
1.1151 raeburn 964: $isredirect = 1;
1.1116 raeburn 965: }
966: } else {
967: ($login_host, $lowest_load) =
968: &compare_server_load($lonhost, $login_host, $lowest_load);
969: if ($login_host eq $lonhost) {
970: $portal_path = '';
1.1151 raeburn 971: $isredirect = '';
1.1116 raeburn 972: }
973: }
974: } else {
1.1076 raeburn 975: ($login_host, $lowest_load) =
1.1116 raeburn 976: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 977: }
978: }
979: if ($login_host ne '') {
1.1116 raeburn 980: $hostname = &hostname($login_host);
1.1076 raeburn 981: }
1.1151 raeburn 982: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 983: }
984:
1.202 matthew 985: # --------------------------------------------- Try to change a user's password
986:
987: sub changepass {
1.799 raeburn 988: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 989: $currentpass = &escape($currentpass);
990: $newpass = &escape($newpass);
1.1030 raeburn 991: my $lonhost = $perlvar{'lonHostID'};
992: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 993: $server);
994: if (! $answer) {
995: &logthis("No reply on password change request to $server ".
996: "by $uname in domain $udom.");
997: } elsif ($answer =~ "^ok") {
998: &logthis("$uname in $udom successfully changed their password ".
999: "on $server.");
1000: } elsif ($answer =~ "^pwchange_failure") {
1001: &logthis("$uname in $udom was unable to change their password ".
1002: "on $server. The action was blocked by either lcpasswd ".
1003: "or pwchange");
1004: } elsif ($answer =~ "^non_authorized") {
1005: &logthis("$uname in $udom did not get their password correct when ".
1006: "attempting to change it on $server.");
1007: } elsif ($answer =~ "^auth_mode_error") {
1008: &logthis("$uname in $udom attempted to change their password despite ".
1009: "not being locally or internally authenticated on $server.");
1010: } elsif ($answer =~ "^unknown_user") {
1011: &logthis("$uname in $udom attempted to change their password ".
1012: "on $server but were unable to because $server is not ".
1013: "their home server.");
1014: } elsif ($answer =~ "^refused") {
1015: &logthis("$server refused to change $uname in $udom password because ".
1016: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1017: } elsif ($answer =~ "invalid_client") {
1018: &logthis("$server refused to change $uname in $udom password because ".
1019: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1020: }
1021: return $answer;
1.1 albertel 1022: }
1023:
1.169 harris41 1024: # ----------------------- Try to determine user's current authentication scheme
1025:
1026: sub queryauthenticate {
1027: my ($uname,$udom)=@_;
1.456 albertel 1028: my $uhome=&homeserver($uname,$udom);
1029: if (!$uhome) {
1030: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1031: return 'no_host';
1032: }
1033: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1034: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1035: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1036: }
1.456 albertel 1037: return $answer;
1.169 harris41 1038: }
1039:
1.1 albertel 1040: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1041:
1.1 albertel 1042: sub authenticate {
1.1073 raeburn 1043: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1044: $upass=&escape($upass);
1045: $uname= &LONCAPA::clean_username($uname);
1.836 www 1046: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1047: my $newhome;
1.836 www 1048: if ((!$uhome) || ($uhome eq 'no_host')) {
1049: # Maybe the machine was offline and only re-appeared again recently?
1050: &reconlonc();
1051: # One more
1.952 raeburn 1052: $uhome=&homeserver($uname,$udom,1);
1053: if (($uhome eq 'no_host') && $checkdefauth) {
1054: if (defined(&domain($udom,'primary'))) {
1055: $newhome=&domain($udom,'primary');
1056: }
1057: if ($newhome ne '') {
1058: $uhome = $newhome;
1059: }
1060: }
1.836 www 1061: if ((!$uhome) || ($uhome eq 'no_host')) {
1062: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1063: return 'no_host';
1064: }
1.1 albertel 1065: }
1.1073 raeburn 1066: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1067: if ($answer eq 'authorized') {
1.952 raeburn 1068: if ($newhome) {
1069: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1070: return 'no_account_on_host';
1071: } else {
1072: &logthis("User $uname at $udom authorized by $uhome");
1073: return $uhome;
1074: }
1.471 albertel 1075: }
1076: if ($answer eq 'non_authorized') {
1077: &logthis("User $uname at $udom rejected by $uhome");
1078: return 'no_host';
1.9 www 1079: }
1.471 albertel 1080: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1081: return 'no_host';
1082: }
1083:
1.1073 raeburn 1084: sub can_host_session {
1.1074 raeburn 1085: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1086: my $canhost = 1;
1.1074 raeburn 1087: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1088: if (ref($remotesessions) eq 'HASH') {
1089: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1090: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1091: $canhost = 0;
1092: } else {
1093: $canhost = 1;
1094: }
1095: }
1096: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1097: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1098: $canhost = 1;
1099: } else {
1100: $canhost = 0;
1101: }
1102: }
1103: if ($canhost) {
1104: if ($remotesessions->{'version'} ne '') {
1105: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1106: if ($reqmajor ne '' && $reqminor ne '') {
1107: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1108: my $major = $1;
1109: my $minor = $2;
1110: if (($major < $reqmajor ) ||
1111: (($major == $reqmajor) && ($minor < $reqminor))) {
1112: $canhost = 0;
1113: }
1114: } else {
1115: $canhost = 0;
1116: }
1117: }
1118: }
1119: }
1120: }
1121: if ($canhost) {
1122: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1123: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1124: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1125: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1126: if (($uint_dom ne '') &&
1127: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1128: $canhost = 0;
1129: } else {
1130: $canhost = 1;
1131: }
1132: }
1133: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1134: if (($uint_dom ne '') &&
1135: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1136: $canhost = 1;
1137: } else {
1138: $canhost = 0;
1139: }
1140: }
1141: }
1142: }
1143: return $canhost;
1144: }
1145:
1.1083 raeburn 1146: sub spare_can_host {
1147: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1148: my $canhost=1;
1149: my @intdoms;
1150: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1151: if (ref($internet_names) eq 'ARRAY') {
1152: @intdoms = @{$internet_names};
1153: }
1154: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1155: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1156: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1157: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1158: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1159: $canhost = &can_host_session($udom,$try_server,$remoterev,
1160: $remotesessions,
1161: $defdomdefaults{'hostedsessions'});
1162: }
1163: return $canhost;
1164: }
1165:
1.1123 raeburn 1166: sub this_host_spares {
1167: my ($dom) = @_;
1.1126 raeburn 1168: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1169: my @hosts = ¤t_machine_ids();
1170: foreach my $lonhost (@hosts) {
1171: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1172: $dom_in_use = $dom;
1173: $lonhost_in_use = $lonhost;
1.1123 raeburn 1174: last;
1175: }
1176: }
1.1126 raeburn 1177: if ($dom_in_use ne '') {
1178: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1179: }
1180: if (ref($result) ne 'HASH') {
1181: $lonhost_in_use = $perlvar{'lonHostID'};
1182: $dom_in_use = &host_domain($lonhost_in_use);
1183: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1184: if (ref($result) ne 'HASH') {
1185: $result = \%spareid;
1186: }
1187: }
1188: return $result;
1189: }
1190:
1191: sub spares_for_offload {
1192: my ($dom_in_use,$lonhost_in_use) = @_;
1193: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1194: if (defined($cached)) {
1195: return $result;
1196: } else {
1.1126 raeburn 1197: my $cachetime = 60*60*24;
1198: my %domconfig =
1199: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1200: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1201: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1202: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1203: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1204: }
1205: }
1206: }
1207: }
1.1126 raeburn 1208: return;
1.1123 raeburn 1209: }
1210:
1.1129 raeburn 1211: sub get_lonbalancer_config {
1212: my ($servers) = @_;
1213: my ($currbalancer,$currtargets);
1214: if (ref($servers) eq 'HASH') {
1215: foreach my $server (keys(%{$servers})) {
1216: my %what = (
1217: spareid => 1,
1218: perlvar => 1,
1219: );
1220: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1221: if ($result eq 'ok') {
1222: if (ref($returnhash) eq 'HASH') {
1223: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1224: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1225: $currbalancer = $server;
1226: $currtargets = {};
1227: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1228: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1229: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1230: }
1231: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1232: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1233: }
1234: }
1235: last;
1236: }
1237: }
1238: }
1239: }
1240: }
1241: }
1242: return ($currbalancer,$currtargets);
1243: }
1244:
1245: sub check_loadbalancing {
1246: my ($uname,$udom) = @_;
1.1172.2.12 raeburn 1247: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1248: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1249: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1250: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1251: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1252: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1253: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1254: my $serverhomedom = &host_domain($lonhost);
1255:
1256: my $cachetime = 60*60*24;
1257:
1258: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1259: $dom_in_use = $udom;
1260: $homeintdom = 1;
1261: } else {
1262: $dom_in_use = $serverhomedom;
1263: }
1264: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1265: unless (defined($cached)) {
1266: my %domconfig =
1267: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1268: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1269: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1270: }
1271: }
1272: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1273: ($is_balancer,$currtargets,$currrules) =
1274: &check_balancer_result($result,@hosts);
1.1129 raeburn 1275: if ($is_balancer) {
1276: if (ref($currrules) eq 'HASH') {
1277: if ($homeintdom) {
1278: if ($uname ne '') {
1279: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1280: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1281: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1282: $rule_in_effect = $currrules->{'_LC_author'};
1283: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1284: $rule_in_effect = $currrules->{'_LC_adv'}
1285: }
1286: }
1287: if ($rule_in_effect eq '') {
1288: my %userenv = &userenvironment($udom,$uname,'inststatus');
1289: if ($userenv{'inststatus'} ne '') {
1290: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1291: my ($othertitle,$usertypes,$types) =
1292: &Apache::loncommon::sorted_inst_types($udom);
1293: if (ref($types) eq 'ARRAY') {
1294: foreach my $type (@{$types}) {
1295: if (grep(/^\Q$type\E$/,@statuses)) {
1296: if (exists($currrules->{$type})) {
1297: $rule_in_effect = $currrules->{$type};
1298: }
1299: }
1300: }
1301: }
1302: } else {
1303: if (exists($currrules->{'default'})) {
1304: $rule_in_effect = $currrules->{'default'};
1305: }
1306: }
1307: }
1308: } else {
1309: if (exists($currrules->{'default'})) {
1310: $rule_in_effect = $currrules->{'default'};
1311: }
1312: }
1313: } else {
1314: if ($currrules->{'_LC_external'} ne '') {
1315: $rule_in_effect = $currrules->{'_LC_external'};
1316: }
1317: }
1318: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1319: $uname,$udom);
1320: }
1321: }
1322: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1323: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1324: unless (defined($cached)) {
1325: my %domconfig =
1326: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1327: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1328: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1329: }
1330: }
1331: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1332: ($is_balancer,$currtargets,$currrules) =
1333: &check_balancer_result($result,@hosts);
1334: if ($is_balancer) {
1.1129 raeburn 1335: if (ref($currrules) eq 'HASH') {
1336: if ($currrules->{'_LC_internetdom'} ne '') {
1337: $rule_in_effect = $currrules->{'_LC_internetdom'};
1338: }
1339: }
1340: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1341: $uname,$udom);
1342: }
1343: } else {
1344: if ($perlvar{'lonBalancer'} eq 'yes') {
1345: $is_balancer = 1;
1346: $offloadto = &this_host_spares($dom_in_use);
1347: }
1348: }
1349: } else {
1350: if ($perlvar{'lonBalancer'} eq 'yes') {
1351: $is_balancer = 1;
1352: $offloadto = &this_host_spares($dom_in_use);
1353: }
1354: }
1.1172.2.5 raeburn 1355: if ($is_balancer) {
1356: my $lowest_load = 30000;
1357: if (ref($offloadto) eq 'HASH') {
1358: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1359: foreach my $try_server (@{$offloadto->{'primary'}}) {
1360: ($otherserver,$lowest_load) =
1361: &compare_server_load($try_server,$otherserver,$lowest_load);
1362: }
1.1129 raeburn 1363: }
1.1172.2.5 raeburn 1364: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1365:
1.1172.2.5 raeburn 1366: if (!$found_server) {
1367: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1368: foreach my $try_server (@{$offloadto->{'default'}}) {
1369: ($otherserver,$lowest_load) =
1370: &compare_server_load($try_server,$otherserver,$lowest_load);
1371: }
1372: }
1373: }
1374: } elsif (ref($offloadto) eq 'ARRAY') {
1375: if (@{$offloadto} == 1) {
1376: $otherserver = $offloadto->[0];
1377: } elsif (@{$offloadto} > 1) {
1378: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1379: ($otherserver,$lowest_load) =
1380: &compare_server_load($try_server,$otherserver,$lowest_load);
1381: }
1382: }
1383: }
1.1172.2.5 raeburn 1384: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1385: $is_balancer = 0;
1386: if ($uname ne '' && $udom ne '') {
1387: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1388:
1389: &appenv({'user.loadbalexempt' => $lonhost,
1390: 'user.loadbalcheck.time' => time});
1391: }
1.1129 raeburn 1392: }
1393: }
1394: }
1395: return ($is_balancer,$otherserver);
1396: }
1397:
1.1172.2.12 raeburn 1398: sub check_balancer_result {
1399: my ($result,@hosts) = @_;
1400: my ($is_balancer,$currtargets,$currrules);
1401: if (ref($result) eq 'HASH') {
1402: if ($result->{'lonhost'} ne '') {
1403: my $currbalancer = $result->{'lonhost'};
1404: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1405: $is_balancer = 1;
1406: $currtargets = $result->{'targets'};
1407: $currrules = $result->{'rules'};
1408: }
1409: } else {
1410: foreach my $key (keys(%{$result})) {
1411: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1412: (ref($result->{$key}) eq 'HASH')) {
1413: $is_balancer = 1;
1414: $currrules = $result->{$key}{'rules'};
1415: $currtargets = $result->{$key}{'targets'};
1416: last;
1417: }
1418: }
1419: }
1420: }
1421: return ($is_balancer,$currtargets,$currrules);
1422: }
1423:
1.1129 raeburn 1424: sub get_loadbalancer_targets {
1425: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1426: my $offloadto;
1.1172.2.4 raeburn 1427: if ($rule_in_effect eq 'none') {
1428: return [$perlvar{'lonHostID'}];
1429: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1430: $offloadto = $currtargets;
1431: } else {
1432: if ($rule_in_effect eq 'homeserver') {
1433: my $homeserver = &homeserver($uname,$udom);
1434: if ($homeserver ne 'no_host') {
1435: $offloadto = [$homeserver];
1436: }
1437: } elsif ($rule_in_effect eq 'externalbalancer') {
1438: my %domconfig =
1439: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1440: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1441: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1442: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1443: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1444: }
1445: }
1446: } else {
1.1172.2.7 raeburn 1447: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1448: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1449: if (&hostname($remotebalancer) ne '') {
1450: $offloadto = [$remotebalancer];
1451: }
1452: }
1453: } elsif (&hostname($rule_in_effect) ne '') {
1454: $offloadto = [$rule_in_effect];
1455: }
1456: }
1457: return $offloadto;
1458: }
1459:
1.1127 raeburn 1460: sub internet_dom_servers {
1461: my ($dom) = @_;
1462: my (%uniqservers,%servers);
1463: my $primaryserver = &hostname(&domain($dom,'primary'));
1464: my @machinedoms = &machine_domains($primaryserver);
1465: foreach my $mdom (@machinedoms) {
1466: my %currservers = %servers;
1467: my %server = &get_servers($mdom);
1468: %servers = (%currservers,%server);
1469: }
1470: my %by_hostname;
1471: foreach my $id (keys(%servers)) {
1472: push(@{$by_hostname{$servers{$id}}},$id);
1473: }
1474: foreach my $hostname (sort(keys(%by_hostname))) {
1475: if (@{$by_hostname{$hostname}} > 1) {
1476: my $match = 0;
1477: foreach my $id (@{$by_hostname{$hostname}}) {
1478: if (&host_domain($id) eq $dom) {
1479: $uniqservers{$id} = $hostname;
1480: $match = 1;
1481: }
1482: }
1483: unless ($match) {
1484: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1485: }
1486: } else {
1487: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1488: }
1489: }
1490: return %uniqservers;
1491: }
1492:
1.1 albertel 1493: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1494:
1.599 albertel 1495: my %homecache;
1.1 albertel 1496: sub homeserver {
1.230 stredwic 1497: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1498: my $index="$uname:$udom";
1.426 albertel 1499:
1.599 albertel 1500: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1501:
1502: my %servers = &get_servers($udom,'library');
1503: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1504: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1505: exists($badServerCache{$tryserver}));
1.841 albertel 1506:
1507: my $answer=reply("home:$udom:$uname",$tryserver);
1508: if ($answer eq 'found') {
1509: delete($badServerCache{$tryserver});
1510: return $homecache{$index}=$tryserver;
1511: } elsif ($answer eq 'no_host') {
1512: $badServerCache{$tryserver}=1;
1513: }
1.1 albertel 1514: }
1515: return 'no_host';
1.70 www 1516: }
1517:
1518: # ------------------------------------- Find the usernames behind a list of IDs
1519:
1520: sub idget {
1521: my ($udom,@ids)=@_;
1522: my %returnhash=();
1523:
1.841 albertel 1524: my %servers = &get_servers($udom,'library');
1525: foreach my $tryserver (keys(%servers)) {
1526: my $idlist=join('&',@ids);
1527: $idlist=~tr/A-Z/a-z/;
1528: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1529: my @answer=();
1530: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1531: @answer=split(/\&/,$reply);
1532: } ;
1533: my $i;
1534: for ($i=0;$i<=$#ids;$i++) {
1535: if ($answer[$i]) {
1536: $returnhash{$ids[$i]}=$answer[$i];
1537: }
1538: }
1539: }
1.70 www 1540: return %returnhash;
1541: }
1542:
1543: # ------------------------------------- Find the IDs behind a list of usernames
1544:
1545: sub idrget {
1546: my ($udom,@unames)=@_;
1547: my %returnhash=();
1.800 albertel 1548: foreach my $uname (@unames) {
1549: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1550: }
1.70 www 1551: return %returnhash;
1552: }
1553:
1554: # ------------------------------- Store away a list of names and associated IDs
1555:
1556: sub idput {
1557: my ($udom,%ids)=@_;
1558: my %servers=();
1.800 albertel 1559: foreach my $uname (keys(%ids)) {
1560: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1561: my $uhom=&homeserver($uname,$udom);
1.70 www 1562: if ($uhom ne 'no_host') {
1.800 albertel 1563: my $id=&escape($ids{$uname});
1.70 www 1564: $id=~tr/A-Z/a-z/;
1.800 albertel 1565: my $esc_unam=&escape($uname);
1.70 www 1566: if ($servers{$uhom}) {
1.800 albertel 1567: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1568: } else {
1.800 albertel 1569: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1570: }
1571: }
1.191 harris41 1572: }
1.800 albertel 1573: foreach my $server (keys(%servers)) {
1574: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1575: }
1.344 www 1576: }
1577:
1.1172.2.30 raeburn 1578: # ---------------------------------------- Delete unwanted IDs from ids.db file
1579:
1580: sub iddel {
1581: my ($udom,$idshashref,$uhome)=@_;
1582: my %result=();
1583: unless (ref($idshashref) eq 'HASH') {
1584: return %result;
1585: }
1586: my %servers=();
1587: while (my ($id,$uname) = each(%{$idshashref})) {
1588: my $uhom;
1589: if ($uhome) {
1590: $uhom = $uhome;
1591: } else {
1592: $uhom=&homeserver($uname,$udom);
1593: }
1594: if ($uhom ne 'no_host') {
1595: if ($servers{$uhom}) {
1596: $servers{$uhom}.='&'.&escape($id);
1597: } else {
1598: $servers{$uhom}=&escape($id);
1599: }
1600: }
1601: }
1602: foreach my $server (keys(%servers)) {
1603: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1604: }
1605: return %result;
1606: }
1607:
1.1023 raeburn 1608: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1609: sub dump_dom {
1.1165 droeschl 1610: my ($namespace, $udom, $regexp) = @_;
1611:
1612: $udom ||= $env{'user.domain'};
1613:
1614: return () unless $udom;
1615:
1616: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1617: }
1618:
1.1023 raeburn 1619: # ------------------------------------------ get items from domain db files
1.806 raeburn 1620:
1621: sub get_dom {
1.860 raeburn 1622: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1623: my $items='';
1624: foreach my $item (@$storearr) {
1625: $items.=&escape($item).'&';
1626: }
1627: $items=~s/\&$//;
1.860 raeburn 1628: if (!$udom) {
1629: $udom=$env{'user.domain'};
1630: if (defined(&domain($udom,'primary'))) {
1631: $uhome=&domain($udom,'primary');
1632: } else {
1.874 albertel 1633: undef($uhome);
1.860 raeburn 1634: }
1635: } else {
1636: if (!$uhome) {
1637: if (defined(&domain($udom,'primary'))) {
1638: $uhome=&domain($udom,'primary');
1639: }
1640: }
1641: }
1642: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1643: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1644: my %returnhash;
1.875 albertel 1645: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1646: return %returnhash;
1647: }
1.806 raeburn 1648: my @pairs=split(/\&/,$rep);
1649: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1650: return @pairs;
1651: }
1652: my $i=0;
1653: foreach my $item (@$storearr) {
1654: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1655: $i++;
1656: }
1657: return %returnhash;
1658: } else {
1.880 banghart 1659: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1660: }
1661: }
1662:
1663: # -------------------------------------------- put items in domain db files
1664:
1665: sub put_dom {
1.860 raeburn 1666: my ($namespace,$storehash,$udom,$uhome)=@_;
1667: if (!$udom) {
1668: $udom=$env{'user.domain'};
1669: if (defined(&domain($udom,'primary'))) {
1670: $uhome=&domain($udom,'primary');
1671: } else {
1.874 albertel 1672: undef($uhome);
1.860 raeburn 1673: }
1674: } else {
1675: if (!$uhome) {
1676: if (defined(&domain($udom,'primary'))) {
1677: $uhome=&domain($udom,'primary');
1678: }
1679: }
1680: }
1681: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1682: my $items='';
1683: foreach my $item (keys(%$storehash)) {
1684: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1685: }
1686: $items=~s/\&$//;
1687: return &reply("putdom:$udom:$namespace:$items",$uhome);
1688: } else {
1.860 raeburn 1689: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1690: }
1691: }
1692:
1.1023 raeburn 1693: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1694: sub newput_dom {
1.1023 raeburn 1695: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1696: my $result;
1697: if (!$udom) {
1698: $udom=$env{'user.domain'};
1699: }
1.1023 raeburn 1700: if ($udom) {
1701: my $uname = &get_domainconfiguser($udom);
1702: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1703: }
1704: return $result;
1705: }
1706:
1.1023 raeburn 1707: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1708: sub del_dom {
1.1023 raeburn 1709: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1710: if (ref($storearr) eq 'ARRAY') {
1711: if (!$udom) {
1712: $udom=$env{'user.domain'};
1713: }
1.1023 raeburn 1714: if ($udom) {
1715: my $uname = &get_domainconfiguser($udom);
1716: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1717: }
1718: }
1719: }
1720:
1.1023 raeburn 1721: # ----------------------------------construct domainconfig user for a domain
1722: sub get_domainconfiguser {
1723: my ($udom) = @_;
1724: return $udom.'-domainconfig';
1725: }
1726:
1.837 raeburn 1727: sub retrieve_inst_usertypes {
1728: my ($udom) = @_;
1729: my (%returnhash,@order);
1.989 raeburn 1730: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1731: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1732: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1733: %returnhash = %{$domdefs{'inststatustypes'}};
1734: @order = @{$domdefs{'inststatusorder'}};
1735: } else {
1736: if (defined(&domain($udom,'primary'))) {
1737: my $uhome=&domain($udom,'primary');
1738: my $rep=&reply("inst_usertypes:$udom",$uhome);
1739: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1740: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1741: return (\%returnhash,\@order);
1742: }
1743: my ($hashitems,$orderitems) = split(/:/,$rep);
1744: my @pairs=split(/\&/,$hashitems);
1745: foreach my $item (@pairs) {
1746: my ($key,$value)=split(/=/,$item,2);
1747: $key = &unescape($key);
1748: next if ($key =~ /^error: 2 /);
1749: $returnhash{$key}=&thaw_unescape($value);
1750: }
1751: my @esc_order = split(/\&/,$orderitems);
1752: foreach my $item (@esc_order) {
1753: push(@order,&unescape($item));
1754: }
1755: } else {
1756: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1757: }
1758: }
1759: return (\%returnhash,\@order);
1760: }
1761:
1.868 raeburn 1762: sub is_domainimage {
1763: my ($url) = @_;
1764: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1765: if (&domain($1) ne '') {
1766: return '1';
1767: }
1768: }
1769: return;
1770: }
1771:
1.899 raeburn 1772: sub inst_directory_query {
1773: my ($srch) = @_;
1774: my $udom = $srch->{'srchdomain'};
1775: my %results;
1776: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1777: my $outcome;
1.899 raeburn 1778: if ($homeserver ne '') {
1.904 albertel 1779: my $queryid=&reply("querysend:instdirsearch:".
1780: &escape($srch->{'srchby'}).':'.
1781: &escape($srch->{'srchterm'}).':'.
1782: &escape($srch->{'srchtype'}),$homeserver);
1783: my $host=&hostname($homeserver);
1784: if ($queryid !~/^\Q$host\E\_/) {
1785: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1786: return;
1787: }
1788: my $response = &get_query_reply($queryid);
1789: my $maxtries = 5;
1790: my $tries = 1;
1791: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1792: $response = &get_query_reply($queryid);
1793: $tries ++;
1794: }
1795:
1796: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1797: if ($response eq 'unavailable') {
1798: $outcome = $response;
1799: } else {
1800: $outcome = 'ok';
1801: my @matches = split(/\n/,$response);
1802: foreach my $match (@matches) {
1803: my ($key,$value) = split(/=/,$match);
1804: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1805: }
1.899 raeburn 1806: }
1807: }
1808: }
1.909 raeburn 1809: return ($outcome,%results);
1.899 raeburn 1810: }
1811:
1812: sub usersearch {
1813: my ($srch) = @_;
1814: my $dom = $srch->{'srchdomain'};
1815: my %results;
1816: my %libserv = &all_library();
1817: my $query = 'usersearch';
1818: foreach my $tryserver (keys(%libserv)) {
1819: if (&host_domain($tryserver) eq $dom) {
1820: my $host=&hostname($tryserver);
1821: my $queryid=
1.911 raeburn 1822: &reply("querysend:".&escape($query).':'.
1823: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1824: &escape($srch->{'srchtype'}).':'.
1825: &escape($srch->{'srchterm'}),$tryserver);
1826: if ($queryid !~/^\Q$host\E\_/) {
1827: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1828: next;
1.899 raeburn 1829: }
1830: my $reply = &get_query_reply($queryid);
1831: my $maxtries = 1;
1832: my $tries = 1;
1833: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1834: $reply = &get_query_reply($queryid);
1835: $tries ++;
1836: }
1837: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1838: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1839: } else {
1.911 raeburn 1840: my @matches;
1841: if ($reply =~ /\n/) {
1842: @matches = split(/\n/,$reply);
1843: } else {
1844: @matches = split(/\&/,$reply);
1845: }
1.899 raeburn 1846: foreach my $match (@matches) {
1847: my ($uname,$udom,%userhash);
1.911 raeburn 1848: foreach my $entry (split(/:/,$match)) {
1849: my ($key,$value) =
1850: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1851: $userhash{$key} = $value;
1852: if ($key eq 'username') {
1853: $uname = $value;
1854: } elsif ($key eq 'domain') {
1855: $udom = $value;
1.911 raeburn 1856: }
1.899 raeburn 1857: }
1858: $results{$uname.':'.$udom} = \%userhash;
1859: }
1860: }
1861: }
1862: }
1863: return %results;
1864: }
1865:
1.912 raeburn 1866: sub get_instuser {
1867: my ($udom,$uname,$id) = @_;
1868: my $homeserver = &domain($udom,'primary');
1869: my ($outcome,%results);
1870: if ($homeserver ne '') {
1871: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1872: &escape($id).':'.&escape($udom),$homeserver);
1873: my $host=&hostname($homeserver);
1874: if ($queryid !~/^\Q$host\E\_/) {
1875: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1876: return;
1877: }
1878: my $response = &get_query_reply($queryid);
1879: my $maxtries = 5;
1880: my $tries = 1;
1881: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1882: $response = &get_query_reply($queryid);
1883: $tries ++;
1884: }
1885: if (!&error($response) && $response ne 'refused') {
1886: if ($response eq 'unavailable') {
1887: $outcome = $response;
1888: } else {
1889: $outcome = 'ok';
1890: my @matches = split(/\n/,$response);
1891: foreach my $match (@matches) {
1892: my ($key,$value) = split(/=/,$match);
1893: $results{&unescape($key)} = &thaw_unescape($value);
1894: }
1895: }
1896: }
1897: }
1898: my %userinfo;
1899: if (ref($results{$uname}) eq 'HASH') {
1900: %userinfo = %{$results{$uname}};
1901: }
1902: return ($outcome,%userinfo);
1903: }
1904:
1905: sub inst_rulecheck {
1.923 raeburn 1906: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1907: my %returnhash;
1908: if ($udom ne '') {
1909: if (ref($rules) eq 'ARRAY') {
1910: @{$rules} = map {&escape($_);} (@{$rules});
1911: my $rulestr = join(':',@{$rules});
1912: my $homeserver=&domain($udom,'primary');
1913: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1914: my $response;
1915: if ($item eq 'username') {
1916: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1917: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1918: $homeserver));
1.923 raeburn 1919: } elsif ($item eq 'id') {
1920: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1921: ':'.&escape($id).':'.$rulestr,
1922: $homeserver));
1.945 raeburn 1923: } elsif ($item eq 'selfcreate') {
1924: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1925: &escape($udom).':'.&escape($uname).
1926: ':'.$rulestr,$homeserver));
1.923 raeburn 1927: }
1.912 raeburn 1928: if ($response ne 'refused') {
1929: my @pairs=split(/\&/,$response);
1930: foreach my $item (@pairs) {
1931: my ($key,$value)=split(/=/,$item,2);
1932: $key = &unescape($key);
1933: next if ($key =~ /^error: 2 /);
1934: $returnhash{$key}=&thaw_unescape($value);
1935: }
1936: }
1937: }
1938: }
1939: }
1940: return %returnhash;
1941: }
1942:
1943: sub inst_userrules {
1.923 raeburn 1944: my ($udom,$check) = @_;
1.912 raeburn 1945: my (%ruleshash,@ruleorder);
1946: if ($udom ne '') {
1947: my $homeserver=&domain($udom,'primary');
1948: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1949: my $response;
1950: if ($check eq 'id') {
1951: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1952: $homeserver);
1.943 raeburn 1953: } elsif ($check eq 'email') {
1954: $response=&reply('instemailrules:'.&escape($udom),
1955: $homeserver);
1.923 raeburn 1956: } else {
1957: $response=&reply('instuserrules:'.&escape($udom),
1958: $homeserver);
1959: }
1.912 raeburn 1960: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1961: ($response ne 'unknown_cmd') &&
1.912 raeburn 1962: ($response ne 'no_such_host')) {
1963: my ($hashitems,$orderitems) = split(/:/,$response);
1964: my @pairs=split(/\&/,$hashitems);
1965: foreach my $item (@pairs) {
1966: my ($key,$value)=split(/=/,$item,2);
1967: $key = &unescape($key);
1968: next if ($key =~ /^error: 2 /);
1969: $ruleshash{$key}=&thaw_unescape($value);
1970: }
1971: my @esc_order = split(/\&/,$orderitems);
1972: foreach my $item (@esc_order) {
1973: push(@ruleorder,&unescape($item));
1974: }
1975: }
1976: }
1977: }
1978: return (\%ruleshash,\@ruleorder);
1979: }
1980:
1.976 raeburn 1981: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1982:
1983: sub get_domain_defaults {
1.1172.2.35 raeburn 1984: my ($domain,$ignore_cache) = @_;
1985: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 1986: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 1987: unless ($ignore_cache) {
1988: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1989: if (defined($cached)) {
1990: if (ref($result) eq 'HASH') {
1991: return %{$result};
1992: }
1.943 raeburn 1993: }
1994: }
1995: my %domdefaults;
1996: my %domconfig =
1.989 raeburn 1997: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1998: 'requestcourses','inststatus',
1.1172.2.9 raeburn 1999: 'coursedefaults','usersessions',
2000: 'requestauthor'],$domain);
1.943 raeburn 2001: if (ref($domconfig{'defaults'}) eq 'HASH') {
2002: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2003: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2004: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2005: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2006: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2007: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2008: } else {
2009: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2010: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2011: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2012: }
1.976 raeburn 2013: if (ref($domconfig{'quotas'}) eq 'HASH') {
2014: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2015: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2016: } else {
2017: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2018: }
1.1172.2.6 raeburn 2019: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2020: foreach my $item (@usertools) {
2021: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2022: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2023: }
2024: }
1.1172.2.29 raeburn 2025: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2026: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2027: }
1.976 raeburn 2028: }
1.985 raeburn 2029: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2030: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2031: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2032: }
2033: }
1.1172.2.9 raeburn 2034: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2035: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2036: }
1.989 raeburn 2037: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2038: foreach my $item ('inststatustypes','inststatusorder') {
2039: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2040: }
2041: }
1.1047 raeburn 2042: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.19 raeburn 2043: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2044: $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
2045: $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
1.1172.2.37 raeburn 2046: $domdefaults{'textbookcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'textbook'};
1.1047 raeburn 2047: }
1.1172.2.30 raeburn 2048: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2049: $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
2050: $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
2051: $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};
1.1172.2.37 raeburn 2052: $domdefaults{'textbookquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'textbook'};
1.1172.2.30 raeburn 2053: }
1.1047 raeburn 2054: }
1.1073 raeburn 2055: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2056: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2057: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2058: }
2059: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2060: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2061: }
2062: }
1.1172.2.23 raeburn 2063: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2064: return %domdefaults;
2065: }
2066:
1.344 www 2067: # --------------------------------------------------- Assign a key to a student
2068:
2069: sub assign_access_key {
1.364 www 2070: #
2071: # a valid key looks like uname:udom#comments
2072: # comments are being appended
2073: #
1.498 www 2074: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2075: $kdom=
1.620 albertel 2076: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2077: $knum=
1.620 albertel 2078: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2079: $cdom=
1.620 albertel 2080: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2081: $cnum=
1.620 albertel 2082: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2083: $udom=$env{'user.name'} unless (defined($udom));
2084: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2085: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2086: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2087: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2088: # assigned to this person
2089: # - this should not happen,
1.345 www 2090: # unless something went wrong
2091: # the first time around
2092: # ready to assign
1.364 www 2093: $logentry=$1.'; '.$logentry;
1.496 www 2094: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2095: $kdom,$knum) eq 'ok') {
1.345 www 2096: # key now belongs to user
1.346 www 2097: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2098: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2099: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2100: return 'ok';
2101: } else {
2102: return
2103: 'error: Count not permanently assign key, will need to be re-entered later.';
2104: }
2105: } else {
2106: return 'error: Could not assign key, try again later.';
2107: }
1.364 www 2108: } elsif (!$existing{$ckey}) {
1.345 www 2109: # the key does not exist
2110: return 'error: The key does not exist';
2111: } else {
2112: # the key is somebody else's
2113: return 'error: The key is already in use';
2114: }
1.344 www 2115: }
2116:
1.364 www 2117: # ------------------------------------------ put an additional comment on a key
2118:
2119: sub comment_access_key {
2120: #
2121: # a valid key looks like uname:udom#comments
2122: # comments are being appended
2123: #
2124: my ($ckey,$cdom,$cnum,$logentry)=@_;
2125: $cdom=
1.620 albertel 2126: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2127: $cnum=
1.620 albertel 2128: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2129: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2130: if ($existing{$ckey}) {
2131: $existing{$ckey}.='; '.$logentry;
2132: # ready to assign
1.367 www 2133: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2134: $cdom,$cnum) eq 'ok') {
2135: return 'ok';
2136: } else {
2137: return 'error: Count not store comment.';
2138: }
2139: } else {
2140: # the key does not exist
2141: return 'error: The key does not exist';
2142: }
2143: }
2144:
1.344 www 2145: # ------------------------------------------------------ Generate a set of keys
2146:
2147: sub generate_access_keys {
1.364 www 2148: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2149: $cdom=
1.620 albertel 2150: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2151: $cnum=
1.620 albertel 2152: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2153: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2154: unless (($cdom) && ($cnum)) { return 0; }
2155: if ($number>10000) { return 0; }
2156: sleep(2); # make sure don't get same seed twice
2157: srand(time()^($$+($$<<15))); # from "Programming Perl"
2158: my $total=0;
2159: for (my $i=1;$i<=$number;$i++) {
2160: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2161: sprintf("%lx",int(100000*rand)).'-'.
2162: sprintf("%lx",int(100000*rand));
2163: $newkey=~s/1/g/g; # folks mix up 1 and l
2164: $newkey=~s/0/h/g; # and also 0 and O
2165: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2166: if ($existing{$newkey}) {
2167: $i--;
2168: } else {
1.364 www 2169: if (&put('accesskeys',
2170: { $newkey => '# generated '.localtime().
1.620 albertel 2171: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2172: '; '.$logentry },
2173: $cdom,$cnum) eq 'ok') {
1.344 www 2174: $total++;
2175: }
2176: }
2177: }
1.620 albertel 2178: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2179: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2180: return $total;
2181: }
2182:
2183: # ------------------------------------------------------- Validate an accesskey
2184:
2185: sub validate_access_key {
2186: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2187: $cdom=
1.620 albertel 2188: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2189: $cnum=
1.620 albertel 2190: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2191: $udom=$env{'user.domain'} unless (defined($udom));
2192: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2193: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2194: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2195: }
2196:
2197: # ------------------------------------- Find the section of student in a course
1.652 albertel 2198: sub devalidate_getsection_cache {
2199: my ($udom,$unam,$courseid)=@_;
2200: my $hashid="$udom:$unam:$courseid";
2201: &devalidate_cache_new('getsection',$hashid);
2202: }
1.298 matthew 2203:
1.815 albertel 2204: sub courseid_to_courseurl {
2205: my ($courseid) = @_;
2206: #already url style courseid
2207: return $courseid if ($courseid =~ m{^/});
2208:
2209: if (exists($env{'course.'.$courseid.'.num'})) {
2210: my $cnum = $env{'course.'.$courseid.'.num'};
2211: my $cdom = $env{'course.'.$courseid.'.domain'};
2212: return "/$cdom/$cnum";
2213: }
2214:
2215: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2216: if (exists($courseinfo{'num'})) {
2217: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2218: }
2219:
2220: return undef;
2221: }
2222:
1.298 matthew 2223: sub getsection {
2224: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2225: my $cachetime=1800;
1.551 albertel 2226:
2227: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2228: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2229: if (defined($cached)) { return $result; }
2230:
1.298 matthew 2231: my %Pending;
2232: my %Expired;
2233: #
2234: # Each role can either have not started yet (pending), be active,
2235: # or have expired.
2236: #
2237: # If there is an active role, we are done.
2238: #
2239: # If there is more than one role which has not started yet,
2240: # choose the one which will start sooner
2241: # If there is one role which has not started yet, return it.
2242: #
2243: # If there is more than one expired role, choose the one which ended last.
2244: # If there is a role which has expired, return it.
2245: #
1.815 albertel 2246: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2247: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2248: foreach my $key (keys(%roleshash)) {
1.479 albertel 2249: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2250: my $section=$1;
2251: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2252: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2253: my $now=time;
1.548 albertel 2254: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2255: $Expired{$end}=$section;
2256: next;
2257: }
1.548 albertel 2258: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2259: $Pending{$start}=$section;
2260: next;
2261: }
1.599 albertel 2262: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2263: }
2264: #
2265: # Presumedly there will be few matching roles from the above
2266: # loop and the sorting time will be negligible.
2267: if (scalar(keys(%Pending))) {
2268: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2269: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2270: }
2271: if (scalar(keys(%Expired))) {
2272: my @sorted = sort {$a <=> $b} keys(%Expired);
2273: my $time = pop(@sorted);
1.599 albertel 2274: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2275: }
1.599 albertel 2276: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2277: }
1.70 www 2278:
1.599 albertel 2279: sub save_cache {
2280: &purge_remembered();
1.722 albertel 2281: #&Apache::loncommon::validate_page();
1.620 albertel 2282: undef(%env);
1.780 albertel 2283: undef($env_loaded);
1.599 albertel 2284: }
1.452 albertel 2285:
1.599 albertel 2286: my $to_remember=-1;
2287: my %remembered;
2288: my %accessed;
2289: my $kicks=0;
2290: my $hits=0;
1.849 albertel 2291: sub make_key {
2292: my ($name,$id) = @_;
1.872 albertel 2293: if (length($id) > 65
2294: && length(&escape($id)) > 200) {
2295: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2296: }
1.849 albertel 2297: return &escape($name.':'.$id);
2298: }
2299:
1.599 albertel 2300: sub devalidate_cache_new {
2301: my ($name,$id,$debug) = @_;
2302: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2303: $id=&make_key($name,$id);
1.599 albertel 2304: $memcache->delete($id);
2305: delete($remembered{$id});
2306: delete($accessed{$id});
2307: }
2308:
2309: sub is_cached_new {
2310: my ($name,$id,$debug) = @_;
1.849 albertel 2311: $id=&make_key($name,$id);
1.599 albertel 2312: if (exists($remembered{$id})) {
1.1133 foxr 2313: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2314: $accessed{$id}=[&gettimeofday()];
2315: $hits++;
2316: return ($remembered{$id},1);
2317: }
2318: my $value = $memcache->get($id);
2319: if (!(defined($value))) {
2320: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2321: return (undef,undef);
1.416 albertel 2322: }
1.599 albertel 2323: if ($value eq '__undef__') {
2324: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2325: $value=undef;
2326: }
2327: &make_room($id,$value,$debug);
2328: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2329: return ($value,1);
2330: }
2331:
2332: sub do_cache_new {
2333: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2334: $id=&make_key($name,$id);
1.599 albertel 2335: my $setvalue=$value;
2336: if (!defined($setvalue)) {
2337: $setvalue='__undef__';
2338: }
1.623 albertel 2339: if (!defined($time) ) {
2340: $time=600;
2341: }
1.599 albertel 2342: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2343: my $result = $memcache->set($id,$setvalue,$time);
2344: if (! $result) {
1.872 albertel 2345: &logthis("caching of id -> $id failed");
1.910 albertel 2346: $memcache->disconnect_all();
1.872 albertel 2347: }
1.600 albertel 2348: # need to make a copy of $value
1.919 albertel 2349: &make_room($id,$value,$debug);
1.599 albertel 2350: return $value;
2351: }
2352:
2353: sub make_room {
2354: my ($id,$value,$debug)=@_;
1.919 albertel 2355:
2356: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2357: : $value;
1.599 albertel 2358: if ($to_remember<0) { return; }
2359: $accessed{$id}=[&gettimeofday()];
2360: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2361: my $to_kick;
2362: my $max_time=0;
2363: foreach my $other (keys(%accessed)) {
2364: if (&tv_interval($accessed{$other}) > $max_time) {
2365: $to_kick=$other;
2366: $max_time=&tv_interval($accessed{$other});
2367: }
2368: }
2369: delete($remembered{$to_kick});
2370: delete($accessed{$to_kick});
2371: $kicks++;
2372: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2373: return;
2374: }
2375:
1.599 albertel 2376: sub purge_remembered {
1.604 albertel 2377: #&logthis("Tossing ".scalar(keys(%remembered)));
2378: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2379: undef(%remembered);
2380: undef(%accessed);
1.428 albertel 2381: }
1.70 www 2382: # ------------------------------------- Read an entry from a user's environment
2383:
2384: sub userenvironment {
2385: my ($udom,$unam,@what)=@_;
1.976 raeburn 2386: my $items;
2387: foreach my $item (@what) {
2388: $items.=&escape($item).'&';
2389: }
2390: $items=~s/\&$//;
1.70 www 2391: my %returnhash=();
1.1009 raeburn 2392: my $uhome = &homeserver($unam,$udom);
2393: unless ($uhome eq 'no_host') {
2394: my @answer=split(/\&/,
2395: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2396: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2397: return %returnhash;
2398: }
1.1009 raeburn 2399: my $i;
2400: for ($i=0;$i<=$#what;$i++) {
2401: $returnhash{$what[$i]}=&unescape($answer[$i]);
2402: }
1.70 www 2403: }
2404: return %returnhash;
1.1 albertel 2405: }
2406:
1.617 albertel 2407: # ---------------------------------------------------------- Get a studentphoto
2408: sub studentphoto {
2409: my ($udom,$unam,$ext) = @_;
2410: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2411: if (defined($env{'request.course.id'})) {
1.708 raeburn 2412: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2413: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2414: return(&retrievestudentphoto($udom,$unam,$ext));
2415: } else {
2416: my ($result,$perm_reqd)=
1.707 albertel 2417: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2418: if ($result eq 'ok') {
2419: if (!($perm_reqd eq 'yes')) {
2420: return(&retrievestudentphoto($udom,$unam,$ext));
2421: }
2422: }
2423: }
2424: }
2425: } else {
2426: my ($result,$perm_reqd) =
1.707 albertel 2427: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2428: if ($result eq 'ok') {
2429: if (!($perm_reqd eq 'yes')) {
2430: return(&retrievestudentphoto($udom,$unam,$ext));
2431: }
2432: }
2433: }
2434: return '/adm/lonKaputt/lonlogo_broken.gif';
2435: }
2436:
2437: sub retrievestudentphoto {
2438: my ($udom,$unam,$ext,$type) = @_;
2439: my $home=&Apache::lonnet::homeserver($unam,$udom);
2440: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2441: if ($ret eq 'ok') {
2442: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2443: if ($type eq 'thumbnail') {
2444: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2445: }
2446: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2447: return $tokenurl;
2448: } else {
2449: if ($type eq 'thumbnail') {
2450: return '/adm/lonKaputt/genericstudent_tn.gif';
2451: } else {
2452: return '/adm/lonKaputt/lonlogo_broken.gif';
2453: }
1.617 albertel 2454: }
2455: }
2456:
1.263 www 2457: # -------------------------------------------------------------------- New chat
2458:
2459: sub chatsend {
1.724 raeburn 2460: my ($newentry,$anon,$group)=@_;
1.620 albertel 2461: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2462: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2463: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2464: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2465: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2466: &escape($newentry)).':'.$group,$chome);
1.292 www 2467: }
2468:
2469: # ------------------------------------------ Find current version of a resource
2470:
2471: sub getversion {
2472: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2473: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2474: return ¤tversion(&filelocation('',$fname));
2475: }
2476:
2477: sub currentversion {
2478: my $fname=shift;
2479: my $author=$fname;
2480: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2481: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2482: my $home=&homeserver($uname,$udom);
1.292 www 2483: if ($home eq 'no_host') {
2484: return -1;
2485: }
1.1112 www 2486: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2487: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2488: return -1;
2489: }
1.1112 www 2490: return $answer;
1.263 www 2491: }
2492:
1.1111 www 2493: #
2494: # Return special version number of resource if set by override, empty otherwise
2495: #
2496: sub usedversion {
2497: my $fname=shift;
2498: unless ($fname) { $fname=$env{'request.uri'}; }
2499: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2500: if ($urlversion) { return $urlversion; }
2501: return '';
2502: }
2503:
1.1 albertel 2504: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2505:
1.1 albertel 2506: sub subscribe {
2507: my $fname=shift;
1.761 raeburn 2508: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2509: $fname=~s/[\n\r]//g;
1.1 albertel 2510: my $author=$fname;
2511: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2512: my ($udom,$uname)=split(/\//,$author);
2513: my $home=homeserver($uname,$udom);
1.335 albertel 2514: if ($home eq 'no_host') {
2515: return 'not_found';
1.1 albertel 2516: }
2517: my $answer=reply("sub:$fname",$home);
1.64 www 2518: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2519: $answer.=' by '.$home;
2520: }
1.1 albertel 2521: return $answer;
2522: }
2523:
1.8 www 2524: # -------------------------------------------------------------- Replicate file
2525:
2526: sub repcopy {
2527: my $filename=shift;
1.23 www 2528: $filename=~s/\/+/\//g;
1.1142 raeburn 2529: my $londocroot = $perlvar{'lonDocRoot'};
2530: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2531: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2532: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2533: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2534: return &repcopy_userfile($filename);
2535: }
1.532 albertel 2536: $filename=~s/[\n\r]//g;
1.8 www 2537: my $transname="$filename.in.transfer";
1.828 www 2538: # FIXME: this should flock
1.607 raeburn 2539: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2540: my $remoteurl=subscribe($filename);
1.64 www 2541: if ($remoteurl =~ /^con_lost by/) {
2542: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2543: return 'unavailable';
1.8 www 2544: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2545: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2546: return 'not_found';
1.64 www 2547: } elsif ($remoteurl =~ /^rejected by/) {
2548: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2549: return 'forbidden';
1.20 www 2550: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2551: return 'ok';
1.8 www 2552: } else {
1.290 www 2553: my $author=$filename;
2554: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2555: my ($udom,$uname)=split(/\//,$author);
2556: my $home=homeserver($uname,$udom);
2557: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2558: my @parts=split(/\//,$filename);
2559: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2560: if ($path ne "$londocroot/res") {
1.8 www 2561: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2562: return 'bad_request';
1.8 www 2563: }
2564: my $count;
2565: for ($count=5;$count<$#parts;$count++) {
2566: $path.="/$parts[$count]";
2567: if ((-e $path)!=1) {
2568: mkdir($path,0777);
2569: }
2570: }
2571: my $ua=new LWP::UserAgent;
2572: my $request=new HTTP::Request('GET',"$remoteurl");
2573: my $response=$ua->request($request,$transname);
2574: if ($response->is_error()) {
2575: unlink($transname);
2576: my $message=$response->status_line;
1.672 albertel 2577: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2578: ." LWP get: $message: $filename</font>");
1.607 raeburn 2579: return 'unavailable';
1.8 www 2580: } else {
1.16 www 2581: if ($remoteurl!~/\.meta$/) {
2582: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2583: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2584: if ($mresponse->is_error()) {
2585: unlink($filename.'.meta');
2586: &logthis(
1.672 albertel 2587: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2588: }
2589: }
1.8 www 2590: rename($transname,$filename);
1.607 raeburn 2591: return 'ok';
1.8 www 2592: }
1.290 www 2593: }
1.8 www 2594: }
1.330 www 2595: }
2596:
2597: # ------------------------------------------------ Get server side include body
2598: sub ssi_body {
1.381 albertel 2599: my ($filelink,%form)=@_;
1.606 matthew 2600: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2601: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2602: }
1.953 www 2603: my $output='';
2604: my $response;
1.980 raeburn 2605: if ($filelink=~/^https?\:/) {
1.954 raeburn 2606: ($output,$response)=&externalssi($filelink);
1.953 www 2607: } else {
1.1004 droeschl 2608: $filelink .= $filelink=~/\?/ ? '&' : '?';
2609: $filelink .= 'inhibitmenu=yes';
1.953 www 2610: ($output,$response)=&ssi($filelink,%form);
2611: }
1.778 albertel 2612: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2613: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2614: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2615: if (wantarray) {
2616: return ($output, $response);
2617: } else {
2618: return $output;
2619: }
1.8 www 2620: }
2621:
1.15 www 2622: # --------------------------------------------------------- Server Side Include
2623:
1.782 albertel 2624: sub absolute_url {
2625: my ($host_name) = @_;
2626: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2627: if ($host_name eq '') {
2628: $host_name = $ENV{'SERVER_NAME'};
2629: }
2630: return $protocol.$host_name;
2631: }
2632:
1.942 foxr 2633: #
2634: # Server side include.
2635: # Parameters:
2636: # fn Possibly encrypted resource name/id.
2637: # form Hash that describes how the rendering should be done
2638: # and other things.
1.944 foxr 2639: # Returns:
1.950 raeburn 2640: # Scalar context: The content of the response.
2641: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2642: #
1.15 www 2643: sub ssi {
2644:
1.944 foxr 2645: my ($fn,%form)=@_;
1.15 www 2646: my $ua=new LWP::UserAgent;
1.23 www 2647: my $request;
1.711 albertel 2648:
2649: $form{'no_update_last_known'}=1;
1.895 albertel 2650: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2651: if (%form) {
1.782 albertel 2652: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2653: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2654: } else {
1.782 albertel 2655: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2656: }
2657:
1.15 www 2658: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2659: my $response= $ua->request($request);
1.944 foxr 2660: if (wantarray) {
1.1172.2.3 raeburn 2661: return ($response->content, $response);
1.944 foxr 2662: } else {
1.1172.2.3 raeburn 2663: return $response->content;
1.942 foxr 2664: }
1.324 www 2665: }
2666:
2667: sub externalssi {
2668: my ($url)=@_;
2669: my $ua=new LWP::UserAgent;
2670: my $request=new HTTP::Request('GET',$url);
2671: my $response=$ua->request($request);
1.954 raeburn 2672: if (wantarray) {
2673: return ($response->content, $response);
2674: } else {
2675: return $response->content;
2676: }
1.15 www 2677: }
1.254 www 2678:
1.492 albertel 2679: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2680:
2681: sub allowuploaded {
2682: my ($srcurl,$url)=@_;
2683: $url=&clutter(&declutter($url));
2684: my $dir=$url;
2685: $dir=~s/\/[^\/]+$//;
2686: my %httpref=();
2687: my $httpurl=&hreflocation('',$url);
2688: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2689: &Apache::lonnet::appenv(\%httpref);
1.254 www 2690: }
1.477 raeburn 2691:
1.1172.2.13 raeburn 2692: #
2693: # Determine if the current user should be able to edit a particular resource,
2694: # when viewing in course context.
2695: # (a) When viewing resource used to determine if "Edit" item is included in
2696: # Functions.
2697: # (b) When displaying folder contents in course editor, used to determine if
2698: # "Edit" link will be displayed alongside resource.
2699: #
2700: # input: six args -- filename (decluttered), course number, course domain,
2701: # url, symb (if registered) and group (if this is a group
2702: # item -- e.g., bulletin board, group page etc.).
2703: # output: array of five scalars --
2704: # $cfile -- url for file editing if editable on current server
2705: # $home -- homeserver of resource (i.e., for author if published,
2706: # or course if uploaded.).
2707: # $switchserver -- 1 if server switch will be needed.
2708: # $forceedit -- 1 if icon/link should be to go to edit mode
2709: # $forceview -- 1 if icon/link should be to go to view mode
2710: #
2711:
2712: sub can_edit_resource {
2713: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2714: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2715: #
2716: # For aboutme pages user can only edit his/her own.
2717: #
2718: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2719: my ($sdom,$sname) = ($1,$2);
2720: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2721: $home = $env{'user.home'};
2722: $cfile = $resurl;
2723: if ($env{'form.forceedit'}) {
2724: $forceview = 1;
2725: } else {
2726: $forceedit = 1;
2727: }
2728: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2729: } else {
2730: return;
2731: }
2732: }
2733:
2734: if ($env{'request.course.id'}) {
2735: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2736: if ($group ne '') {
2737: # if this is a group homepage or group bulletin board, check group privs
2738: my $allowed = 0;
2739: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2740: if ((&allowed('mdg',$env{'request.course.id'}.
2741: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2742: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2743: $allowed = 1;
2744: }
2745: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2746: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2747: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2748: $allowed = 1;
2749: }
2750: }
2751: if ($allowed) {
2752: $home=&homeserver($cnum,$cdom);
2753: if ($env{'form.forceedit'}) {
2754: $forceview = 1;
2755: } else {
2756: $forceedit = 1;
2757: }
2758: $cfile = $resurl;
2759: } else {
2760: return;
2761: }
2762: } else {
1.1172.2.15 raeburn 2763: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2764: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2765: return;
2766: }
2767: } elsif (!$crsedit) {
1.1172.2.13 raeburn 2768: #
2769: # No edit allowed where CC has switched to student role.
2770: #
2771: return;
2772: }
2773: }
2774: }
2775:
2776: if ($file ne '') {
2777: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2778: if (&is_course_upload($file,$cnum,$cdom)) {
2779: $uploaded = 1;
2780: $incourse = 1;
2781: if ($file =~/\.(htm|html|css|js|txt)$/) {
2782: $cfile = &hreflocation('',$file);
2783: if ($env{'form.forceedit'}) {
2784: $forceview = 1;
2785: } else {
2786: $forceedit = 1;
2787: }
2788: }
2789: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2790: $incourse = 1;
2791: if ($env{'form.forceedit'}) {
2792: $forceview = 1;
2793: } else {
2794: $forceedit = 1;
2795: }
2796: $cfile = $resurl;
2797: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2798: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2799: $incourse = 1;
2800: if ($env{'form.forceedit'}) {
2801: $forceview = 1;
2802: } else {
2803: $forceedit = 1;
2804: }
2805: $cfile = $resurl;
2806: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2807: $incourse = 1;
2808: $cfile = $resurl.'/smpedit';
2809: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2810: $incourse = 1;
2811: if ($env{'form.forceedit'}) {
2812: $forceview = 1;
2813: } else {
2814: $forceedit = 1;
2815: }
2816: $cfile = $resurl;
1.1172.2.15 raeburn 2817: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2818: $incourse = 1;
2819: if ($env{'form.forceedit'}) {
2820: $forceview = 1;
2821: } else {
2822: $forceedit = 1;
2823: }
2824: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2825: }
2826: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2827: my $template = '/res/lib/templates/simpleproblem.problem';
2828: if (&is_on_map($template)) {
2829: $incourse = 1;
2830: $forceview = 1;
2831: $cfile = $template;
2832: }
2833: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2834: $incourse = 1;
2835: if ($env{'form.forceedit'}) {
2836: $forceview = 1;
2837: } else {
2838: $forceedit = 1;
2839: }
2840: $cfile = $resurl;
2841: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2842: $incourse = 1;
2843: $forceview = 1;
2844: if ($symb) {
2845: my ($map,$id,$res)=&decode_symb($symb);
2846: $env{'request.symb'} = $symb;
2847: $cfile = &clutter($res);
2848: } else {
2849: $cfile = $env{'form.suppurl'};
2850: $cfile =~ s{^http://}{};
2851: $cfile = '/adm/wrapper/ext/'.$cfile;
2852: }
1.1172.2.31 raeburn 2853: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2854: if ($env{'form.forceedit'}) {
2855: $forceview = 1;
2856: } else {
2857: $forceedit = 1;
2858: }
2859: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2860: }
2861: }
2862: if ($uploaded || $incourse) {
2863: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 2864: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 2865: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2866: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2867: # Check that the user has permission to edit this resource
2868: my $setpriv = 1;
2869: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2870: if (defined($cfudom)) {
2871: $home=&homeserver($cfuname,$cfudom);
2872: $cfile=$file;
2873: }
2874: }
2875: if (($cfile ne '') && (!$incourse || $uploaded) &&
2876: (($home ne '') && ($home ne 'no_host'))) {
2877: my @ids=¤t_machine_ids();
2878: unless (grep(/^\Q$home\E$/,@ids)) {
2879: $switchserver=1;
2880: }
2881: }
2882: }
2883: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2884: }
2885:
2886: sub is_course_upload {
2887: my ($file,$cnum,$cdom) = @_;
2888: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2889: $uploadpath =~ s{^\/}{};
2890: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2891: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
2892: return 1;
2893: }
2894: return;
2895: }
2896:
2897: sub in_course {
2898: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2899: if ($hideprivileged) {
2900: my $skipuser;
1.1172.2.23 raeburn 2901: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2902: my @possdoms = ($cdom);
2903: if ($coursehash{'checkforpriv'}) {
2904: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2905: }
2906: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 2907: $skipuser = 1;
2908: if ($coursehash{'nothideprivileged'}) {
2909: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2910: my $user;
2911: if ($item =~ /:/) {
2912: $user = $item;
2913: } else {
2914: $user = join(':',split(/[\@]/,$item));
2915: }
2916: if ($user eq $uname.':'.$udom) {
2917: undef($skipuser);
2918: last;
2919: }
2920: }
2921: }
2922: if ($skipuser) {
2923: return 0;
2924: }
2925: }
2926: }
2927: $type ||= 'any';
2928: if (!defined($cdom) || !defined($cnum)) {
2929: my $cid = $env{'request.course.id'};
2930: $cdom = $env{'course.'.$cid.'.domain'};
2931: $cnum = $env{'course.'.$cid.'.num'};
2932: }
2933: my $typesref;
2934: if (($type eq 'any') || ($type eq 'all')) {
2935: $typesref = ['active','previous','future'];
2936: } elsif ($type eq 'previous' || $type eq 'future') {
2937: $typesref = [$type];
2938: }
2939: my %roles = &get_my_roles($uname,$udom,'userroles',
2940: $typesref,undef,[$cdom]);
2941: my ($tmp) = keys(%roles);
2942: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
2943: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
2944: if (@course_roles > 0) {
2945: return 1;
2946: }
2947: return 0;
2948: }
2949:
1.478 albertel 2950: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2951: # input: action, courseID, current domain, intended
1.637 raeburn 2952: # path to file, source of file, instruction to parse file for objects,
2953: # ref to hash for embedded objects,
2954: # ref to hash for codebase of java objects.
1.1095 raeburn 2955: # reference to scalar to accommodate mime type determined
2956: # from File::MMagic if $parser = parse.
1.637 raeburn 2957: #
1.485 raeburn 2958: # output: url to file (if action was uploaddoc),
2959: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2960: #
1.478 albertel 2961: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2962: # course.
1.477 raeburn 2963: #
1.478 albertel 2964: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2965: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2966: # course's home server.
1.477 raeburn 2967: #
1.478 albertel 2968: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2969: # be copied from $source (current location) to
2970: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2971: # and will then be copied to
2972: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2973: # course's home server.
1.485 raeburn 2974: #
1.481 raeburn 2975: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2976: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2977: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2978: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2979: # in course's home server.
1.637 raeburn 2980: #
1.477 raeburn 2981:
2982: sub process_coursefile {
1.1095 raeburn 2983: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2984: $mimetype)=@_;
1.477 raeburn 2985: my $fetchresult;
1.638 albertel 2986: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2987: if ($action eq 'propagate') {
1.638 albertel 2988: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2989: $home);
1.481 raeburn 2990: } else {
1.477 raeburn 2991: my $fpath = '';
2992: my $fname = $file;
1.478 albertel 2993: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2994: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2995: my $filepath = &build_filepath($fpath);
1.481 raeburn 2996: if ($action eq 'copy') {
2997: if ($source eq '') {
2998: $fetchresult = 'no source file';
2999: return $fetchresult;
3000: } else {
3001: my $destination = $filepath.'/'.$fname;
3002: rename($source,$destination);
3003: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3004: $home);
1.481 raeburn 3005: }
3006: } elsif ($action eq 'uploaddoc') {
3007: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3008: print $fh $env{'form.'.$source};
1.481 raeburn 3009: close($fh);
1.637 raeburn 3010: if ($parser eq 'parse') {
1.1024 raeburn 3011: my $mm = new File::MMagic;
1.1095 raeburn 3012: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3013: if ($type eq 'text/html') {
1.1024 raeburn 3014: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3015: unless ($parse_result eq 'ok') {
3016: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3017: }
1.637 raeburn 3018: }
1.1095 raeburn 3019: if (ref($mimetype)) {
3020: $$mimetype = $type;
3021: }
1.637 raeburn 3022: }
1.477 raeburn 3023: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3024: $home);
1.481 raeburn 3025: if ($fetchresult eq 'ok') {
3026: return '/uploaded/'.$fpath.'/'.$fname;
3027: } else {
3028: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3029: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3030: return '/adm/notfound.html';
3031: }
1.477 raeburn 3032: }
3033: }
1.485 raeburn 3034: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3035: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3036: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3037: }
3038: return $fetchresult;
3039: }
3040:
1.637 raeburn 3041: sub build_filepath {
3042: my ($fpath) = @_;
3043: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3044: unless ($fpath eq '') {
3045: my @parts=split('/',$fpath);
3046: foreach my $part (@parts) {
3047: $filepath.= '/'.$part;
3048: if ((-e $filepath)!=1) {
3049: mkdir($filepath,0777);
3050: }
3051: }
3052: }
3053: return $filepath;
3054: }
3055:
3056: sub store_edited_file {
1.638 albertel 3057: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3058: my $file = $primary_url;
3059: $file =~ s#^/uploaded/$docudom/$docuname/##;
3060: my $fpath = '';
3061: my $fname = $file;
3062: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3063: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3064: my $filepath = &build_filepath($fpath);
3065: open(my $fh,'>'.$filepath.'/'.$fname);
3066: print $fh $content;
3067: close($fh);
1.638 albertel 3068: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3069: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3070: $home);
1.637 raeburn 3071: if ($$fetchresult eq 'ok') {
3072: return '/uploaded/'.$fpath.'/'.$fname;
3073: } else {
1.638 albertel 3074: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3075: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3076: return '/adm/notfound.html';
3077: }
3078: }
3079:
1.531 albertel 3080: sub clean_filename {
1.831 albertel 3081: my ($fname,$args)=@_;
1.315 www 3082: # Replace Windows backslashes by forward slashes
1.257 www 3083: $fname=~s/\\/\//g;
1.831 albertel 3084: if (!$args->{'keep_path'}) {
3085: # Get rid of everything but the actual filename
3086: $fname=~s/^.*\/([^\/]+)$/$1/;
3087: }
1.315 www 3088: # Replace spaces by underscores
3089: $fname=~s/\s+/\_/g;
3090: # Replace all other weird characters by nothing
1.831 albertel 3091: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3092: # Replace all .\d. sequences with _\d. so they no longer look like version
3093: # numbers
3094: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3095: return $fname;
3096: }
1.1051 raeburn 3097: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3098: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3099: # image with the same aspect ratio as the original, but with dimensions which do
3100: # not exceed $resizewidth and $resizeheight.
3101:
1.984 neumanie 3102: sub resizeImage {
1.1051 raeburn 3103: my ($img_path,$resizewidth,$resizeheight) = @_;
3104: my $ima = Image::Magick->new;
3105: my $resized;
3106: if (-e $img_path) {
3107: $ima->Read($img_path);
3108: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3109: my $width = $ima->Get('width');
3110: my $height = $ima->Get('height');
3111: if ($width > $resizewidth) {
3112: my $factor = $width/$resizewidth;
3113: my $newheight = $height/$factor;
3114: $ima->Scale(width=>$resizewidth,height=>$newheight);
3115: $resized = 1;
3116: }
3117: }
3118: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3119: my $width = $ima->Get('width');
3120: my $height = $ima->Get('height');
3121: if ($height > $resizeheight) {
3122: my $factor = $height/$resizeheight;
3123: my $newwidth = $width/$factor;
3124: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3125: $resized = 1;
3126: }
3127: }
3128: if ($resized) {
3129: $ima->Write($img_path);
3130: }
3131: }
3132: return;
1.977 amueller 3133: }
3134:
1.608 albertel 3135: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3136: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3137: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3138: # $context - possible values: coursedoc, existingfile, overwrite,
3139: # canceloverwrite, or ''.
3140: # if 'coursedoc': upload to the current course
3141: # if 'existingfile': write file to tmp/overwrites directory
3142: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3143: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3144: # $subdir - directory in userfile to store the file into
1.858 raeburn 3145: # $parser - instruction to parse file for objects ($parser = parse)
3146: # $allfiles - reference to hash for embedded objects
3147: # $codebase - reference to hash for codebase of java objects
3148: # $desuname - username for permanent storage of uploaded file
3149: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3150: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3151: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3152: # $resizewidth - width (pixels) to which to resize uploaded image
3153: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3154: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3155: # from File::MMagic.
1.858 raeburn 3156: #
1.686 albertel 3157: # output: url of file in userspace, or error: <message>
3158: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3159:
1.531 albertel 3160: sub userfileupload {
1.1090 raeburn 3161: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3162: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3163: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3164: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3165: $fname=&clean_filename($fname);
1.1090 raeburn 3166: # See if there is anything left
1.257 www 3167: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3168: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3169: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3170: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3171: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3172: my $now = time;
1.1090 raeburn 3173: my $filepath;
1.1095 raeburn 3174: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3175: $filepath = 'tmp/helprequests/'.$now;
3176: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3177: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3178: '_'.$env{'user.domain'}.'/pending';
3179: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3180: my ($docuname,$docudom);
3181: if ($destudom) {
3182: $docudom = $destudom;
3183: } else {
3184: $docudom = $env{'user.domain'};
3185: }
3186: if ($destuname) {
3187: $docuname = $destuname;
3188: } else {
3189: $docuname = $env{'user.name'};
3190: }
3191: if (exists($env{'form.group'})) {
3192: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3193: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3194: }
3195: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3196: if ($context eq 'canceloverwrite') {
3197: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3198: if (-e $tempfile) {
3199: my @info = stat($tempfile);
3200: if ($info[9] eq $env{'form.timestamp'}) {
3201: unlink($tempfile);
3202: }
3203: }
3204: return;
1.523 raeburn 3205: }
3206: }
1.1090 raeburn 3207: # Create the directory if not present
1.741 raeburn 3208: my @parts=split(/\//,$filepath);
3209: my $fullpath = $perlvar{'lonDaemons'};
3210: for (my $i=0;$i<@parts;$i++) {
3211: $fullpath .= '/'.$parts[$i];
3212: if ((-e $fullpath)!=1) {
3213: mkdir($fullpath,0777);
3214: }
3215: }
3216: open(my $fh,'>'.$fullpath.'/'.$fname);
3217: print $fh $env{'form.'.$formname};
3218: close($fh);
1.1090 raeburn 3219: if ($context eq 'existingfile') {
3220: my @info = stat($fullpath.'/'.$fname);
3221: return ($fullpath.'/'.$fname,$info[9]);
3222: } else {
3223: return $fullpath.'/'.$fname;
3224: }
1.523 raeburn 3225: }
1.995 raeburn 3226: if ($subdir eq 'scantron') {
3227: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3228: } else {
1.995 raeburn 3229: $fname="$subdir/$fname";
3230: }
1.1090 raeburn 3231: if ($context eq 'coursedoc') {
1.638 albertel 3232: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3233: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3234: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3235: return &finishuserfileupload($docuname,$docudom,
3236: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3237: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3238: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3239: } else {
1.1172.2.21 raeburn 3240: if ($env{'form.folder'}) {
3241: $fname=$env{'form.folder'}.'/'.$fname;
3242: }
1.638 albertel 3243: return &process_coursefile('uploaddoc',$docuname,$docudom,
3244: $fname,$formname,$parser,
1.1095 raeburn 3245: $allfiles,$codebase,$mimetype);
1.481 raeburn 3246: }
1.719 banghart 3247: } elsif (defined($destuname)) {
3248: my $docuname=$destuname;
3249: my $docudom=$destudom;
1.860 raeburn 3250: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3251: $parser,$allfiles,$codebase,
1.1051 raeburn 3252: $thumbwidth,$thumbheight,
1.1095 raeburn 3253: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3254: } else {
1.638 albertel 3255: my $docuname=$env{'user.name'};
3256: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3257: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3258: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3259: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3260: }
1.860 raeburn 3261: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3262: $parser,$allfiles,$codebase,
1.1051 raeburn 3263: $thumbwidth,$thumbheight,
1.1095 raeburn 3264: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3265: }
1.271 www 3266: }
3267:
3268: sub finishuserfileupload {
1.860 raeburn 3269: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3270: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3271: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3272: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3273:
1.860 raeburn 3274: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3275: $file=$fname;
3276: if ($fname=~m|/|) {
3277: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3278: $path.=$fnamepath.'/';
3279: }
1.259 www 3280: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3281: my $count;
3282: for ($count=4;$count<=$#parts;$count++) {
3283: $filepath.="/$parts[$count]";
3284: if ((-e $filepath)!=1) {
3285: mkdir($filepath,0777);
3286: }
3287: }
1.984 neumanie 3288:
1.258 www 3289: # Save the file
3290: {
1.701 albertel 3291: if (!open(FH,'>'.$filepath.'/'.$file)) {
3292: &logthis('Failed to create '.$filepath.'/'.$file);
3293: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3294: return '/adm/notfound.html';
3295: }
1.1090 raeburn 3296: if ($context eq 'overwrite') {
1.1117 foxr 3297: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3298: my $target = $filepath.'/'.$file;
3299: if (-e $source) {
3300: my @info = stat($source);
3301: if ($info[9] eq $env{'form.timestamp'}) {
3302: unless (&File::Copy::move($source,$target)) {
3303: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3304: return "Moving from $source failed";
3305: }
3306: } else {
3307: return "Temporary file: $source had unexpected date/time for last modification";
3308: }
3309: } else {
3310: return "Temporary file: $source missing";
3311: }
3312: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3313: &logthis('Failed to write to '.$filepath.'/'.$file);
3314: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3315: return '/adm/notfound.html';
3316: }
1.570 albertel 3317: close(FH);
1.1051 raeburn 3318: if ($resizewidth && $resizeheight) {
3319: my $mm = new File::MMagic;
3320: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3321: if ($mime_type =~ m{^image/}) {
3322: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3323: }
1.977 amueller 3324: }
1.258 www 3325: }
1.1152 raeburn 3326: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3327: if (ref($mimetype)) {
3328: if ($$mimetype eq '') {
3329: my $mm = new File::MMagic;
3330: my $type = $mm->checktype_filename($filepath.'/'.$file);
3331: $$mimetype = $type;
3332: }
3333: }
3334: }
1.637 raeburn 3335: if ($parser eq 'parse') {
1.1152 raeburn 3336: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3337: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3338: $allfiles,$codebase);
3339: unless ($parse_result eq 'ok') {
3340: &logthis('Failed to parse '.$filepath.$file.
3341: ' for embedded media: '.$parse_result);
3342: }
1.637 raeburn 3343: }
3344: }
1.860 raeburn 3345: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3346: my $input = $filepath.'/'.$file;
3347: my $output = $filepath.'/'.'tn-'.$file;
3348: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3349: system("convert -sample $thumbsize $input $output");
3350: if (-e $filepath.'/'.'tn-'.$file) {
3351: $fetchthumb = 1;
3352: }
3353: }
1.858 raeburn 3354:
1.259 www 3355: # Notify homeserver to grep it
3356: #
1.984 neumanie 3357: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3358: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3359: if ($fetchresult eq 'ok') {
1.860 raeburn 3360: if ($fetchthumb) {
3361: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3362: if ($thumbresult ne 'ok') {
3363: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3364: $docuhome.': '.$thumbresult);
3365: }
3366: }
1.259 www 3367: #
1.258 www 3368: # Return the URL to it
1.494 albertel 3369: return '/uploaded/'.$path.$file;
1.263 www 3370: } else {
1.494 albertel 3371: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3372: ': '.$fetchresult);
1.263 www 3373: return '/adm/notfound.html';
1.858 raeburn 3374: }
1.493 albertel 3375: }
3376:
1.637 raeburn 3377: sub extract_embedded_items {
1.961 raeburn 3378: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3379: my @state = ();
1.1164 raeburn 3380: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3381: my %javafiles = (
3382: codebase => '',
3383: code => '',
3384: archive => ''
3385: );
3386: my %mediafiles = (
3387: src => '',
3388: movie => '',
3389: );
1.648 raeburn 3390: my $p;
3391: if ($content) {
3392: $p = HTML::LCParser->new($content);
3393: } else {
1.961 raeburn 3394: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3395: }
1.641 albertel 3396: while (my $t=$p->get_token()) {
1.640 albertel 3397: if ($t->[0] eq 'S') {
3398: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3399: push(@state, $tagname);
1.648 raeburn 3400: if (lc($tagname) eq 'allow') {
3401: &add_filetype($allfiles,$attr->{'src'},'src');
3402: }
1.640 albertel 3403: if (lc($tagname) eq 'img') {
3404: &add_filetype($allfiles,$attr->{'src'},'src');
3405: }
1.886 albertel 3406: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3407: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3408: &add_filetype($allfiles,$attr->{'href'},'href');
3409: }
1.886 albertel 3410: }
1.645 raeburn 3411: if (lc($tagname) eq 'script') {
1.1164 raeburn 3412: my $src;
1.645 raeburn 3413: if ($attr->{'archive'} =~ /\.jar$/i) {
3414: &add_filetype($allfiles,$attr->{'archive'},'archive');
3415: } else {
1.1164 raeburn 3416: if ($attr->{'src'} ne '') {
3417: $src = $attr->{'src'};
3418: &add_filetype($allfiles,$src,'src');
3419: }
3420: }
3421: my $text = $p->get_trimmed_text();
3422: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3423: my @swfargs = split(/,/,$1);
3424: foreach my $item (@swfargs) {
3425: $item =~ s/["']//g;
3426: $item =~ s/^\s+//;
3427: $item =~ s/\s+$//;
3428: }
3429: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3430: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3431: push(@{$related{$swfargs[0]}},$swfargs[2]);
3432: } else {
3433: $related{$swfargs[0]} = [$swfargs[2]];
3434: }
3435: }
1.645 raeburn 3436: }
3437: }
3438: if (lc($tagname) eq 'link') {
3439: if (lc($attr->{'rel'}) eq 'stylesheet') {
3440: &add_filetype($allfiles,$attr->{'href'},'href');
3441: }
3442: }
1.640 albertel 3443: if (lc($tagname) eq 'object' ||
3444: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3445: foreach my $item (keys(%javafiles)) {
3446: $javafiles{$item} = '';
3447: }
1.1164 raeburn 3448: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3449: $lastids{lc($tagname)} = $attr->{'id'};
3450: }
1.640 albertel 3451: }
3452: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3453: my $name = lc($attr->{'name'});
3454: foreach my $item (keys(%javafiles)) {
3455: if ($name eq $item) {
3456: $javafiles{$item} = $attr->{'value'};
3457: last;
3458: }
3459: }
1.1164 raeburn 3460: my $pathfrom;
1.640 albertel 3461: foreach my $item (keys(%mediafiles)) {
3462: if ($name eq $item) {
1.1164 raeburn 3463: $pathfrom = $attr->{'value'};
3464: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3465: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3466: last;
3467: }
3468: }
1.1164 raeburn 3469: if ($name eq 'flashvars') {
3470: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3471: }
3472: if ($pathfrom ne '') {
3473: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3474: $pathfrom);
3475: }
1.640 albertel 3476: }
3477: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3478: foreach my $item (keys(%javafiles)) {
3479: if ($attr->{$item}) {
3480: $javafiles{$item} = $attr->{$item};
3481: last;
3482: }
3483: }
3484: foreach my $item (keys(%mediafiles)) {
3485: if ($attr->{$item}) {
3486: &add_filetype($allfiles,$attr->{$item},$item);
3487: last;
3488: }
3489: }
1.1164 raeburn 3490: if (lc($tagname) eq 'embed') {
3491: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3492: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3493: $attr->{'src'});
3494: }
3495: }
1.640 albertel 3496: }
1.1172.2.35 raeburn 3497: if (lc($tagname) eq 'iframe') {
3498: my $src = $attr->{'src'} ;
3499: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3500: &add_filetype($allfiles,$src,'src');
3501: } elsif ($src =~ m{^/}) {
3502: if ($env{'request.course.id'}) {
3503: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3504: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3505: my $url = &hreflocation('',$fullpath);
3506: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3507: my $relpath = $1;
3508: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3509: &add_filetype($allfiles,$1,'src');
3510: }
3511: }
3512: }
3513: }
3514: }
1.1164 raeburn 3515: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3516: pop(@state);
1.1164 raeburn 3517: }
1.640 albertel 3518: } elsif ($t->[0] eq 'E') {
3519: my ($tagname) = ($t->[1]);
3520: if ($javafiles{'codebase'} ne '') {
3521: $javafiles{'codebase'} .= '/';
3522: }
3523: if (lc($tagname) eq 'applet' ||
3524: lc($tagname) eq 'object' ||
3525: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3526: ) {
3527: foreach my $item (keys(%javafiles)) {
3528: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3529: my $file=$javafiles{'codebase'}.$javafiles{$item};
3530: &add_filetype($allfiles,$file,$item);
3531: }
3532: }
3533: }
3534: pop @state;
3535: }
3536: }
1.1164 raeburn 3537: foreach my $id (sort(keys(%flashvars))) {
3538: if ($shockwave{$id} ne '') {
3539: my @pairs = split(/\&/,$flashvars{$id});
3540: foreach my $pair (@pairs) {
3541: my ($key,$value) = split(/\=/,$pair);
3542: if ($key eq 'thumb') {
3543: &add_filetype($allfiles,$value,$key);
3544: } elsif ($key eq 'content') {
3545: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3546: my ($ext) = ($value =~ /\.([^.]+)$/);
3547: if ($ext ne '') {
3548: &add_filetype($allfiles,$path.$value,$ext);
3549: }
3550: }
3551: }
3552: }
3553: }
1.637 raeburn 3554: return 'ok';
3555: }
3556:
1.639 albertel 3557: sub add_filetype {
3558: my ($allfiles,$file,$type)=@_;
3559: if (exists($allfiles->{$file})) {
3560: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3561: push(@{$allfiles->{$file}}, &escape($type));
3562: }
3563: } else {
3564: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3565: }
3566: }
3567:
1.1164 raeburn 3568: sub embedded_dependency {
3569: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3570: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3571: if (($identifier ne '') &&
3572: (ref($related->{$identifier}) eq 'ARRAY') &&
3573: ($pathfrom ne '')) {
3574: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3575: foreach my $dep (@{$related->{$identifier}}) {
3576: &add_filetype($allfiles,$path.$dep,'object');
3577: }
3578: }
3579: }
3580: return;
3581: }
3582:
1.493 albertel 3583: sub removeuploadedurl {
1.984 neumanie 3584: my ($url)=@_;
3585: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3586: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3587: }
3588:
3589: sub removeuserfile {
3590: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3591: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3592: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3593: if ($result eq 'ok') {
1.798 raeburn 3594: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3595: my $metafile = $fname.'.meta';
3596: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3597: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3598: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3599: my $sqlresult =
1.823 albertel 3600: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3601: 'portfolio_metadata',$group,
3602: 'delete');
1.798 raeburn 3603: }
3604: }
3605: return $result;
1.257 www 3606: }
1.15 www 3607:
1.530 albertel 3608: sub mkdiruserfile {
3609: my ($docuname,$docudom,$dir)=@_;
3610: my $home=&homeserver($docuname,$docudom);
3611: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3612: }
3613:
1.531 albertel 3614: sub renameuserfile {
3615: my ($docuname,$docudom,$old,$new)=@_;
3616: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3617: my $result = &reply("renameuserfile:$docudom:$docuname:".
3618: &escape("$old").':'.&escape("$new"),$home);
3619: if ($result eq 'ok') {
3620: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3621: my $oldmeta = $old.'.meta';
3622: my $newmeta = $new.'.meta';
3623: my $metaresult =
3624: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3625: my $url = "/uploaded/$docudom/$docuname/$old";
3626: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3627: my $sqlresult =
1.823 albertel 3628: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3629: 'portfolio_metadata',$group,
3630: 'delete');
1.798 raeburn 3631: }
3632: }
3633: return $result;
1.531 albertel 3634: }
3635:
1.14 www 3636: # ------------------------------------------------------------------------- Log
3637:
3638: sub log {
3639: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3640: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3641: }
3642:
3643: # ------------------------------------------------------------------ Course Log
1.352 www 3644: #
3645: # This routine flushes several buffers of non-mission-critical nature
3646: #
1.157 www 3647:
3648: sub flushcourselogs {
1.352 www 3649: &logthis('Flushing log buffers');
3650: #
3651: # course logs
3652: # This is a log of all transactions in a course, which can be used
3653: # for data mining purposes
3654: #
3655: # It also collects the courseid database, which lists last transaction
3656: # times and course titles for all courseids
3657: #
3658: my %courseidbuffer=();
1.921 raeburn 3659: foreach my $crsid (keys(%courselogs)) {
1.352 www 3660: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3661: &escape($courselogs{$crsid}),
3662: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3663: delete $courselogs{$crsid};
3664: } else {
3665: &logthis('Failed to flush log buffer for '.$crsid);
3666: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3667: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3668: " exceeded maximum size, deleting.</font>");
3669: delete $courselogs{$crsid};
3670: }
1.352 www 3671: }
1.920 raeburn 3672: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3673: 'description' => $coursedescrbuf{$crsid},
3674: 'inst_code' => $courseinstcodebuf{$crsid},
3675: 'type' => $coursetypebuf{$crsid},
3676: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3677: };
1.191 harris41 3678: }
1.352 www 3679: #
3680: # Write course id database (reverse lookup) to homeserver of courses
3681: # Is used in pickcourse
3682: #
1.840 albertel 3683: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3684: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3685: $courseidbuffer{$crs_home},
3686: $crs_home,'timeonly');
1.352 www 3687: }
3688: #
3689: # File accesses
3690: # Writes to the dynamic metadata of resources to get hit counts, etc.
3691: #
1.449 matthew 3692: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3693: if ($entry =~ /___count$/) {
3694: my ($dom,$name);
1.807 albertel 3695: ($dom,$name,undef)=
1.811 albertel 3696: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3697: if (! defined($dom) || $dom eq '' ||
3698: ! defined($name) || $name eq '') {
1.620 albertel 3699: my $cid = $env{'request.course.id'};
3700: $dom = $env{'request.'.$cid.'.domain'};
3701: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3702: }
1.450 matthew 3703: my $value = $accesshash{$entry};
3704: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3705: my %temphash=($url => $value);
1.449 matthew 3706: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3707: if ($result eq 'ok') {
3708: delete $accesshash{$entry};
3709: }
3710: } else {
1.811 albertel 3711: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3712: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3713: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3714: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3715: delete $accesshash{$entry};
3716: }
1.185 www 3717: }
1.191 harris41 3718: }
1.352 www 3719: #
3720: # Roles
3721: # Reverse lookup of user roles for course faculty/staff and co-authorship
3722: #
1.800 albertel 3723: foreach my $entry (keys(%userrolehash)) {
1.351 www 3724: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3725: split(/\:/,$entry);
3726: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3727: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3728: $rudom,$runame) eq 'ok') {
3729: delete $userrolehash{$entry};
3730: }
3731: }
1.662 raeburn 3732: #
3733: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3734: #
3735: my %domrolebuffer = ();
1.1000 raeburn 3736: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3737: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3738: if ($domrolebuffer{$rudom}) {
3739: $domrolebuffer{$rudom}.='&'.&escape($entry).
3740: '='.&escape($domainrolehash{$entry});
3741: } else {
3742: $domrolebuffer{$rudom}.=&escape($entry).
3743: '='.&escape($domainrolehash{$entry});
3744: }
3745: delete $domainrolehash{$entry};
3746: }
3747: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3748: my %servers = &get_servers($dom,'library');
3749: foreach my $tryserver (keys(%servers)) {
3750: unless (&reply('domroleput:'.$dom.':'.
3751: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3752: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3753: }
1.662 raeburn 3754: }
3755: }
1.186 www 3756: $dumpcount++;
1.157 www 3757: }
3758:
3759: sub courselog {
3760: my $what=shift;
1.158 www 3761: $what=time.':'.$what;
1.620 albertel 3762: unless ($env{'request.course.id'}) { return ''; }
3763: $coursedombuf{$env{'request.course.id'}}=
3764: $env{'course.'.$env{'request.course.id'}.'.domain'};
3765: $coursenumbuf{$env{'request.course.id'}}=
3766: $env{'course.'.$env{'request.course.id'}.'.num'};
3767: $coursehombuf{$env{'request.course.id'}}=
3768: $env{'course.'.$env{'request.course.id'}.'.home'};
3769: $coursedescrbuf{$env{'request.course.id'}}=
3770: $env{'course.'.$env{'request.course.id'}.'.description'};
3771: $courseinstcodebuf{$env{'request.course.id'}}=
3772: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3773: $courseownerbuf{$env{'request.course.id'}}=
3774: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3775: $coursetypebuf{$env{'request.course.id'}}=
3776: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3777: if (defined $courselogs{$env{'request.course.id'}}) {
3778: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3779: } else {
1.620 albertel 3780: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3781: }
1.620 albertel 3782: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3783: &flushcourselogs();
3784: }
1.158 www 3785: }
3786:
3787: sub courseacclog {
3788: my $fnsymb=shift;
1.620 albertel 3789: unless ($env{'request.course.id'}) { return ''; }
3790: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3791: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3792: $what.=':POST';
1.583 matthew 3793: # FIXME: Probably ought to escape things....
1.800 albertel 3794: foreach my $key (keys(%env)) {
3795: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3796: my $formitem = $1;
3797: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3798: $what.=':'.$formitem.'='.$env{$key};
3799: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3800: $what.=':'.$formitem.'='.$env{$key};
3801: }
1.158 www 3802: }
1.191 harris41 3803: }
1.583 matthew 3804: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3805: # FIXME: We should not be depending on a form parameter that someone
3806: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3807: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3808: $what.= ':POST';
3809: # FIXME: Probably ought to escape things....
3810: foreach my $element ('courseexp','crsfulltext','crsrelated',
3811: 'crsdiscuss') {
1.620 albertel 3812: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3813: }
3814: }
1.158 www 3815: }
3816: &courselog($what);
1.149 www 3817: }
3818:
1.185 www 3819: sub countacc {
3820: my $url=&declutter(shift);
1.458 matthew 3821: return if (! defined($url) || $url eq '');
1.620 albertel 3822: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3823: #
3824: # Mark that this url was used in this course
3825: #
1.620 albertel 3826: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3827: #
3828: # Increase the access count for this resource in this child process
3829: #
1.281 www 3830: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3831: $accesshash{$key}++;
1.185 www 3832: }
1.349 www 3833:
1.361 www 3834: sub linklog {
3835: my ($from,$to)=@_;
3836: $from=&declutter($from);
3837: $to=&declutter($to);
3838: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3839: $accesshash{$to.'___'.$from.'___goto'}=1;
3840: }
1.1160 www 3841:
3842: sub statslog {
3843: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3844: if ($users<2) { return; }
3845: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3846: 'course' => $env{'request.course.id'},
3847: 'sections' => '"all"',
3848: 'num_students' => $users,
3849: 'part' => $part,
3850: 'symb' => $symb,
3851: 'mean_tries' => $av_attempts,
3852: 'deg_of_diff' => $degdiff});
3853: foreach my $key (keys(%dynstore)) {
3854: $accesshash{$key}=$dynstore{$key};
3855: }
3856: }
1.361 www 3857:
1.349 www 3858: sub userrolelog {
3859: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3860: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3861: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3862: $userrolehash
3863: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3864: =$tend.':'.$tstart;
1.662 raeburn 3865: }
1.1169 droeschl 3866: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3867: $userrolehash
3868: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3869: =$tend.':'.$tstart;
3870: }
1.1169 droeschl 3871: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3872: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3873: $domainrolehash
3874: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3875: = $tend.':'.$tstart;
3876: }
1.351 www 3877: }
3878:
1.957 raeburn 3879: sub courserolelog {
3880: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 3881: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3882: my $cdom = $1;
3883: my $cnum = $2;
3884: my $sec = $3;
3885: my $namespace = 'rolelog';
3886: my %storehash = (
3887: role => $trole,
3888: start => $tstart,
3889: end => $tend,
3890: selfenroll => $selfenroll,
3891: context => $context,
3892: );
3893: if ($trole eq 'gr') {
3894: $namespace = 'groupslog';
3895: $storehash{'group'} = $sec;
3896: } else {
3897: $storehash{'section'} = $sec;
3898: }
3899: &write_log('course',$namespace,\%storehash,$delflag,$username,
3900: $domain,$cnum,$cdom);
3901: if (($trole ne 'st') || ($sec ne '')) {
3902: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3903: }
3904: }
3905: return;
3906: }
3907:
1.1172.2.9 raeburn 3908: sub domainrolelog {
3909: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3910: if ($area =~ m{^/($match_domain)/$}) {
3911: my $cdom = $1;
3912: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3913: my $namespace = 'rolelog';
3914: my %storehash = (
3915: role => $trole,
3916: start => $tstart,
3917: end => $tend,
3918: context => $context,
3919: );
3920: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3921: $domain,$domconfiguser,$cdom);
3922: }
3923: return;
3924:
3925: }
3926:
3927: sub coauthorrolelog {
3928: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3929: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3930: my $audom = $1;
3931: my $auname = $2;
3932: my $namespace = 'rolelog';
3933: my %storehash = (
3934: role => $trole,
3935: start => $tstart,
3936: end => $tend,
3937: context => $context,
3938: );
3939: &write_log('author',$namespace,\%storehash,$delflag,$username,
3940: $domain,$auname,$audom);
3941: }
3942: return;
3943: }
3944:
1.351 www 3945: sub get_course_adv_roles {
1.948 raeburn 3946: my ($cid,$codes) = @_;
1.620 albertel 3947: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3948: my %coursehash=&coursedescription($cid);
1.988 raeburn 3949: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3950: my %nothide=();
1.800 albertel 3951: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3952: if ($user !~ /:/) {
3953: $nothide{join(':',split(/[\@]/,$user))}=1;
3954: } else {
3955: $nothide{$user}=1;
3956: }
1.470 www 3957: }
1.1172.2.23 raeburn 3958: my @possdoms = ($coursehash{'domain'});
3959: if ($coursehash{'checkforpriv'}) {
3960: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3961: }
1.351 www 3962: my %returnhash=();
3963: my %dumphash=
3964: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3965: my $now=time;
1.997 raeburn 3966: my %privileged;
1.1000 raeburn 3967: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3968: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3969: if (($tstart) && ($tstart<0)) { next; }
3970: if (($tend) && ($tend<$now)) { next; }
3971: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3972: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3973: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 3974: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 3975: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3976: if ($role eq 'cr') { next; }
1.948 raeburn 3977: if ($codes) {
3978: if ($section) { $role .= ':'.$section; }
3979: if ($returnhash{$role}) {
3980: $returnhash{$role}.=','.$username.':'.$domain;
3981: } else {
3982: $returnhash{$role}=$username.':'.$domain;
3983: }
1.351 www 3984: } else {
1.988 raeburn 3985: my $key=&plaintext($role,$crstype);
1.973 bisitz 3986: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3987: if ($returnhash{$key}) {
3988: $returnhash{$key}.=','.$username.':'.$domain;
3989: } else {
3990: $returnhash{$key}=$username.':'.$domain;
3991: }
1.351 www 3992: }
1.948 raeburn 3993: }
1.400 www 3994: return %returnhash;
3995: }
3996:
3997: sub get_my_roles {
1.937 raeburn 3998: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3999: unless (defined($uname)) { $uname=$env{'user.name'}; }
4000: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4001: my (%dumphash,%nothide);
1.1086 raeburn 4002: if ($context eq 'userroles') {
1.1166 raeburn 4003: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4004: } else {
1.1172.2.23 raeburn 4005: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4006: if ($hidepriv) {
4007: my %coursehash=&coursedescription($udom.'_'.$uname);
4008: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4009: if ($user !~ /:/) {
4010: $nothide{join(':',split(/[\@]/,$user))} = 1;
4011: } else {
4012: $nothide{$user} = 1;
4013: }
4014: }
4015: }
1.858 raeburn 4016: }
1.400 www 4017: my %returnhash=();
4018: my $now=time;
1.999 raeburn 4019: my %privileged;
1.800 albertel 4020: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4021: my ($role,$tend,$tstart);
4022: if ($context eq 'userroles') {
1.1149 raeburn 4023: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4024: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4025: } else {
4026: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4027: }
1.400 www 4028: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4029: my $status = 'active';
1.939 raeburn 4030: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4031: $status = 'previous';
4032: }
4033: if (($tstart) && ($now<$tstart)) {
4034: $status = 'future';
4035: }
4036: if (ref($types) eq 'ARRAY') {
4037: if (!grep(/^\Q$status\E$/,@{$types})) {
4038: next;
4039: }
4040: } else {
4041: if ($status ne 'active') {
4042: next;
4043: }
4044: }
1.867 raeburn 4045: my ($rolecode,$username,$domain,$section,$area);
4046: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4047: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4048: (undef,$domain,$username,$section) = split(/\//,$area);
4049: } else {
4050: ($role,$username,$domain,$section) = split(/\:/,$entry);
4051: }
1.832 raeburn 4052: if (ref($roledoms) eq 'ARRAY') {
4053: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4054: next;
4055: }
4056: }
4057: if (ref($roles) eq 'ARRAY') {
4058: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4059: if ($role =~ /^cr\//) {
4060: if (!grep(/^cr$/,@{$roles})) {
4061: next;
4062: }
1.1104 raeburn 4063: } elsif ($role =~ /^gr\//) {
4064: if (!grep(/^gr$/,@{$roles})) {
4065: next;
4066: }
1.922 raeburn 4067: } else {
4068: next;
4069: }
1.832 raeburn 4070: }
1.867 raeburn 4071: }
1.937 raeburn 4072: if ($hidepriv) {
1.1172.2.23 raeburn 4073: my @privroles = ('dc','su');
1.999 raeburn 4074: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4075: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4076: } else {
1.1172.2.23 raeburn 4077: my $possdoms = [$domain];
4078: if (ref($roledoms) eq 'ARRAY') {
4079: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4080: }
1.1172.2.23 raeburn 4081: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4082: if (!$nothide{$username.':'.$domain}) {
4083: next;
4084: }
4085: }
1.937 raeburn 4086: }
4087: }
1.933 raeburn 4088: if ($withsec) {
4089: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4090: $tstart.':'.$tend;
4091: } else {
4092: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4093: }
1.832 raeburn 4094: }
1.373 www 4095: return %returnhash;
1.399 www 4096: }
4097:
4098: # ----------------------------------------------------- Frontpage Announcements
4099: #
4100: #
4101:
4102: sub postannounce {
4103: my ($server,$text)=@_;
1.844 albertel 4104: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4105: unless ($text=~/\w/) { $text=''; }
4106: return &reply('setannounce:'.&escape($text),$server);
4107: }
4108:
4109: sub getannounce {
1.448 albertel 4110:
4111: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4112: my $announcement='';
1.800 albertel 4113: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4114: close($fh);
1.399 www 4115: if ($announcement=~/\w/) {
4116: return
4117: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4118: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4119: } else {
4120: return '';
4121: }
4122: } else {
4123: return '';
4124: }
1.351 www 4125: }
1.353 www 4126:
4127: # ---------------------------------------------------------- Course ID routines
4128: # Deal with domain's nohist_courseid.db files
4129: #
4130:
4131: sub courseidput {
1.921 raeburn 4132: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4133: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4134: my $outcome;
4135: if ($caller eq 'timeonly') {
4136: my $cids = '';
4137: foreach my $item (keys(%$storehash)) {
4138: $cids.=&escape($item).'&';
4139: }
4140: $cids=~s/\&$//;
4141: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4142: $coursehome);
4143: } else {
4144: my $items = '';
4145: foreach my $item (keys(%$storehash)) {
4146: $items.= &escape($item).'='.
4147: &freeze_escape($$storehash{$item}).'&';
4148: }
4149: $items=~s/\&$//;
4150: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4151: $coursehome);
1.918 raeburn 4152: }
4153: if ($outcome eq 'unknown_cmd') {
4154: my $what;
4155: foreach my $cid (keys(%$storehash)) {
4156: $what .= &escape($cid).'=';
1.921 raeburn 4157: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4158: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4159: }
4160: $what =~ s/\:$/&/;
4161: }
4162: $what =~ s/\&$//;
4163: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4164: } else {
4165: return $outcome;
4166: }
1.353 www 4167: }
4168:
4169: sub courseiddump {
1.921 raeburn 4170: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4171: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4172: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 4173: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4174: $hasuniquecode)=@_;
1.918 raeburn 4175: my $as_hash = 1;
4176: my %returnhash;
4177: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4178: my %libserv = &all_library();
4179: foreach my $tryserver (keys(%libserv)) {
4180: if ( ( $hostidflag == 1
4181: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4182: || (!defined($hostidflag)) ) {
4183:
1.918 raeburn 4184: if (($domfilter eq '') ||
4185: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4186: my $rep;
4187: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4188: $rep = &LONCAPA::Lond::dump_course_id_handler(
4189: join(":", (&host_domain($tryserver), $sincefilter,
4190: &escape($descfilter), &escape($instcodefilter),
4191: &escape($ownerfilter), &escape($coursefilter),
4192: &escape($typefilter), &escape($regexp_ok),
4193: $as_hash, &escape($selfenrollonly),
4194: &escape($catfilter), $showhidden, $caller,
4195: &escape($cloner), &escape($cc_clone), $cloneonly,
4196: &escape($createdbefore), &escape($createdafter),
1.1172.2.38 raeburn 4197: &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1172.2.22 raeburn 4198: } else {
4199: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4200: $sincefilter.':'.&escape($descfilter).':'.
4201: &escape($instcodefilter).':'.&escape($ownerfilter).
4202: ':'.&escape($coursefilter).':'.&escape($typefilter).
4203: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4204: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4205: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4206: &escape($cc_clone).':'.$cloneonly.':'.
4207: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.38 raeburn 4208: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1172.2.22 raeburn 4209: $tryserver);
4210: }
4211:
1.918 raeburn 4212: my @pairs=split(/\&/,$rep);
4213: foreach my $item (@pairs) {
4214: my ($key,$value)=split(/\=/,$item,2);
4215: $key = &unescape($key);
4216: next if ($key =~ /^error: 2 /);
4217: my $result = &thaw_unescape($value);
4218: if (ref($result) eq 'HASH') {
4219: $returnhash{$key}=$result;
4220: } else {
1.921 raeburn 4221: my @responses = split(/:/,$value);
4222: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4223: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4224: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4225: }
1.1008 raeburn 4226: }
1.353 www 4227: }
4228: }
4229: }
4230: }
4231: return %returnhash;
4232: }
4233:
1.1055 raeburn 4234: sub courselastaccess {
4235: my ($cdom,$cnum,$hostidref) = @_;
4236: my %returnhash;
4237: if ($cdom && $cnum) {
4238: my $chome = &homeserver($cnum,$cdom);
4239: if ($chome ne 'no_host') {
4240: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4241: &extract_lastaccess(\%returnhash,$rep);
4242: }
4243: } else {
4244: if (!$cdom) { $cdom=''; }
4245: my %libserv = &all_library();
4246: foreach my $tryserver (keys(%libserv)) {
4247: if (ref($hostidref) eq 'ARRAY') {
4248: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4249: }
4250: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4251: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4252: &extract_lastaccess(\%returnhash,$rep);
4253: }
4254: }
4255: }
4256: return %returnhash;
4257: }
4258:
4259: sub extract_lastaccess {
4260: my ($returnhash,$rep) = @_;
4261: if (ref($returnhash) eq 'HASH') {
4262: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4263: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4264: $rep eq '') {
4265: my @pairs=split(/\&/,$rep);
4266: foreach my $item (@pairs) {
4267: my ($key,$value)=split(/\=/,$item,2);
4268: $key = &unescape($key);
4269: next if ($key =~ /^error: 2 /);
4270: $returnhash->{$key} = &thaw_unescape($value);
4271: }
4272: }
4273: }
4274: return;
4275: }
4276:
1.658 raeburn 4277: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4278:
4279: sub dcmailput {
1.685 raeburn 4280: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4281: my $status = &Apache::lonnet::critical(
1.740 www 4282: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4283: &escape($message),$server);
1.662 raeburn 4284: return $status;
4285: }
4286:
1.658 raeburn 4287: sub dcmaildump {
4288: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4289: my %returnhash=();
1.846 albertel 4290:
4291: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4292: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4293: &escape($enddate).':';
4294: my @esc_senders=map { &escape($_)} @$senders;
4295: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4296: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4297: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4298: if (($key) && ($value)) {
4299: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4300: }
4301: }
4302: }
4303: return %returnhash;
4304: }
1.662 raeburn 4305: # ---------------------------------------------------------- Domain roles
4306:
4307: sub get_domain_roles {
4308: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4309: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4310: $startdate = '.';
4311: }
1.1018 raeburn 4312: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4313: $enddate = '.';
4314: }
1.922 raeburn 4315: my $rolelist;
4316: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4317: $rolelist = join('&',@{$roles});
1.922 raeburn 4318: }
1.662 raeburn 4319: my %personnel = ();
1.841 albertel 4320:
4321: my %servers = &get_servers($dom,'library');
4322: foreach my $tryserver (keys(%servers)) {
4323: %{$personnel{$tryserver}}=();
4324: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4325: &escape($startdate).':'.
4326: &escape($enddate).':'.
4327: &escape($rolelist), $tryserver))) {
4328: my ($key,$value) = split(/\=/,$line,2);
4329: if (($key) && ($value)) {
4330: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4331: }
4332: }
1.662 raeburn 4333: }
4334: return %personnel;
4335: }
1.658 raeburn 4336:
1.1057 www 4337: # ----------------------------------------------------------- Interval timing
1.149 www 4338:
1.1153 www 4339: {
4340: # Caches needed for speedup of navmaps
4341: # We don't want to cache this for very long at all (5 seconds at most)
4342: #
4343: # The user for whom we cache
4344: my $cachedkey='';
4345: # The cached times for this user
4346: my %cachedtimes=();
4347: # When this was last done
4348: my $cachedtime=();
4349:
4350: sub load_all_first_access {
1.1154 raeburn 4351: my ($uname,$udom)=@_;
1.1156 www 4352: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 4353: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4354: return;
4355: }
4356: $cachedtime=time;
4357: $cachedkey=$uname.':'.$udom;
4358: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4359: }
4360:
1.504 albertel 4361: sub get_first_access {
1.1162 raeburn 4362: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4363: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4364: if ($argsymb) { $symb=$argsymb; }
4365: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4366: if ($argmap) { $map = $argmap; }
1.926 albertel 4367: if ($type eq 'course') {
4368: $res='course';
4369: } elsif ($type eq 'map') {
1.588 albertel 4370: $res=&symbread($map);
4371: } else {
4372: $res=$symb;
4373: }
1.1153 www 4374: &load_all_first_access($uname,$udom);
4375: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4376: }
4377:
4378: sub set_first_access {
1.1162 raeburn 4379: my ($type,$interval)=@_;
1.790 albertel 4380: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4381: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4382: if ($type eq 'course') {
4383: $res='course';
4384: } elsif ($type eq 'map') {
1.588 albertel 4385: $res=&symbread($map);
4386: } else {
4387: $res=$symb;
4388: }
1.1153 www 4389: $cachedkey='';
1.1162 raeburn 4390: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4391: if (!$firstaccess) {
1.1162 raeburn 4392: my $start = time;
4393: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4394: $udom,$uname);
4395: if ($putres eq 'ok') {
4396: &put('timerinterval',{"$courseid\0$res"=>$interval},
4397: $udom,$uname);
4398: &appenv(
4399: {
4400: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4401: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4402: }
4403: );
4404: }
4405: return $putres;
1.505 albertel 4406: }
4407: return 'already_set';
1.504 albertel 4408: }
1.1153 www 4409: }
1.1172.2.32 raeburn 4410:
4411: sub checkout {
4412: my ($symb,$tuname,$tudom,$tcrsid)=@_;
4413: my $now=time;
4414: my $lonhost=$perlvar{'lonHostID'};
4415: my $infostr=&escape(
4416: 'CHECKOUTTOKEN&'.
4417: $tuname.'&'.
4418: $tudom.'&'.
4419: $tcrsid.'&'.
4420: $symb.'&'.
4421: $now.'&'.$ENV{'REMOTE_ADDR'});
4422: my $token=&reply('tmpput:'.$infostr,$lonhost);
4423: if ($token=~/^error\:/) {
4424: &logthis("<font color=\"blue\">WARNING: ".
4425: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
4426: "</font>");
4427: return '';
4428: }
4429:
4430: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
4431: $token=~tr/a-z/A-Z/;
4432:
4433: my %infohash=('resource.0.outtoken' => $token,
4434: 'resource.0.checkouttime' => $now,
4435: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
4436:
4437: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4438: return '';
4439: } else {
4440: &logthis("<font color=\"blue\">WARNING: ".
4441: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
4442: "</font>");
4443: }
4444:
4445: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4446: &escape('Checkout '.$infostr.' - '.
4447: $token)) ne 'ok') {
4448: return '';
4449: } else {
4450: &logthis("<font color=\"blue\">WARNING: ".
4451: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
4452: "</font>");
4453: }
4454: return $token;
4455: }
4456:
4457: # ------------------------------------------------------------ Check in an item
4458:
4459: sub checkin {
4460: my $token=shift;
4461: my $now=time;
4462: my ($ta,$tb,$lonhost)=split(/\*/,$token);
4463: $lonhost=~tr/A-Z/a-z/;
4464: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
4465: $dtoken=~s/\W/\_/g;
4466: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
4467: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
4468:
4469: unless (($tuname) && ($tudom)) {
4470: &logthis('Check in '.$token.' ('.$dtoken.') failed');
4471: return '';
4472: }
4473:
4474: unless (&allowed('mgr',$tcrsid)) {
4475: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
4476: $env{'user.name'}.' - '.$env{'user.domain'});
4477: return '';
4478: }
4479:
4480: my %infohash=('resource.0.intoken' => $token,
4481: 'resource.0.checkintime' => $now,
4482: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
4483:
4484: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4485: return '';
4486: }
4487:
4488: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4489: &escape('Checkin - '.$token)) ne 'ok') {
4490: return '';
4491: }
4492:
4493: return ($symb,$tuname,$tudom,$tcrsid);
4494: }
4495:
1.110 www 4496: # --------------------------------------------- Set Expire Date for Spreadsheet
4497:
4498: sub expirespread {
4499: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4500: my $cid=$env{'request.course.id'};
1.110 www 4501: if ($cid) {
4502: my $now=time;
4503: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4504: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4505: $env{'course.'.$cid.'.num'}.
1.110 www 4506: ':nohist_expirationdates:'.
4507: &escape($key).'='.$now,
1.620 albertel 4508: $env{'course.'.$cid.'.home'})
1.110 www 4509: }
4510: return 'ok';
1.14 www 4511: }
4512:
1.109 www 4513: # ----------------------------------------------------- Devalidate Spreadsheets
4514:
4515: sub devalidate {
1.325 www 4516: my ($symb,$uname,$udom)=@_;
1.620 albertel 4517: my $cid=$env{'request.course.id'};
1.109 www 4518: if ($cid) {
1.391 matthew 4519: # delete the stored spreadsheets for
4520: # - the student level sheet of this user in course's homespace
4521: # - the assessment level sheet for this resource
4522: # for this user in user's homespace
1.553 albertel 4523: # - current conditional state info
1.325 www 4524: my $key=$uname.':'.$udom.':';
1.109 www 4525: my $status=
1.299 matthew 4526: &del('nohist_calculatedsheets',
1.391 matthew 4527: [$key.'studentcalc:'],
1.620 albertel 4528: $env{'course.'.$cid.'.domain'},
4529: $env{'course.'.$cid.'.num'})
1.133 albertel 4530: .' '.
4531: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4532: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4533: unless ($status eq 'ok ok') {
4534: &logthis('Could not devalidate spreadsheet '.
1.325 www 4535: $uname.' at '.$udom.' for '.
1.109 www 4536: $symb.': '.$status);
1.133 albertel 4537: }
1.553 albertel 4538: &delenv('user.state.'.$cid);
1.109 www 4539: }
4540: }
4541:
1.265 albertel 4542: sub get_scalar {
4543: my ($string,$end) = @_;
4544: my $value;
4545: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4546: $value = $1;
4547: } elsif ($$string =~ s/^([^&]*?)&//) {
4548: $value = $1;
4549: }
4550: return &unescape($value);
4551: }
4552:
4553: sub array2str {
4554: my (@array) = @_;
4555: my $result=&arrayref2str(\@array);
4556: $result=~s/^__ARRAY_REF__//;
4557: $result=~s/__END_ARRAY_REF__$//;
4558: return $result;
4559: }
4560:
1.204 albertel 4561: sub arrayref2str {
4562: my ($arrayref) = @_;
1.265 albertel 4563: my $result='__ARRAY_REF__';
1.204 albertel 4564: foreach my $elem (@$arrayref) {
1.265 albertel 4565: if(ref($elem) eq 'ARRAY') {
4566: $result.=&arrayref2str($elem).'&';
4567: } elsif(ref($elem) eq 'HASH') {
4568: $result.=&hashref2str($elem).'&';
4569: } elsif(ref($elem)) {
4570: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4571: } else {
4572: $result.=&escape($elem).'&';
4573: }
4574: }
4575: $result=~s/\&$//;
1.265 albertel 4576: $result .= '__END_ARRAY_REF__';
1.204 albertel 4577: return $result;
4578: }
4579:
1.168 albertel 4580: sub hash2str {
1.204 albertel 4581: my (%hash) = @_;
4582: my $result=&hashref2str(\%hash);
1.265 albertel 4583: $result=~s/^__HASH_REF__//;
4584: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4585: return $result;
4586: }
4587:
4588: sub hashref2str {
4589: my ($hashref)=@_;
1.265 albertel 4590: my $result='__HASH_REF__';
1.800 albertel 4591: foreach my $key (sort(keys(%$hashref))) {
4592: if (ref($key) eq 'ARRAY') {
4593: $result.=&arrayref2str($key).'=';
4594: } elsif (ref($key) eq 'HASH') {
4595: $result.=&hashref2str($key).'=';
4596: } elsif (ref($key)) {
1.265 albertel 4597: $result.='=';
1.800 albertel 4598: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4599: } else {
1.1132 raeburn 4600: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4601: }
4602:
1.800 albertel 4603: if(ref($hashref->{$key}) eq 'ARRAY') {
4604: $result.=&arrayref2str($hashref->{$key}).'&';
4605: } elsif(ref($hashref->{$key}) eq 'HASH') {
4606: $result.=&hashref2str($hashref->{$key}).'&';
4607: } elsif(ref($hashref->{$key})) {
1.265 albertel 4608: $result.='&';
1.800 albertel 4609: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4610: } else {
1.800 albertel 4611: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4612: }
4613: }
1.168 albertel 4614: $result=~s/\&$//;
1.265 albertel 4615: $result .= '__END_HASH_REF__';
1.168 albertel 4616: return $result;
4617: }
4618:
4619: sub str2hash {
1.265 albertel 4620: my ($string)=@_;
4621: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4622: return %$hash;
4623: }
4624:
4625: sub str2hashref {
1.168 albertel 4626: my ($string) = @_;
1.265 albertel 4627:
4628: my %hash;
4629:
4630: if($string !~ /^__HASH_REF__/) {
4631: if (! ($string eq '' || !defined($string))) {
4632: $hash{'error'}='Not hash reference';
4633: }
4634: return (\%hash, $string);
4635: }
4636:
4637: $string =~ s/^__HASH_REF__//;
4638:
4639: while($string !~ /^__END_HASH_REF__/) {
4640: #key
4641: my $key='';
4642: if($string =~ /^__HASH_REF__/) {
4643: ($key, $string)=&str2hashref($string);
4644: if(defined($key->{'error'})) {
4645: $hash{'error'}='Bad data';
4646: return (\%hash, $string);
4647: }
4648: } elsif($string =~ /^__ARRAY_REF__/) {
4649: ($key, $string)=&str2arrayref($string);
4650: if($key->[0] eq 'Array reference error') {
4651: $hash{'error'}='Bad data';
4652: return (\%hash, $string);
4653: }
4654: } else {
4655: $string =~ s/^(.*?)=//;
1.267 albertel 4656: $key=&unescape($1);
1.265 albertel 4657: }
4658: $string =~ s/^=//;
4659:
4660: #value
4661: my $value='';
4662: if($string =~ /^__HASH_REF__/) {
4663: ($value, $string)=&str2hashref($string);
4664: if(defined($value->{'error'})) {
4665: $hash{'error'}='Bad data';
4666: return (\%hash, $string);
4667: }
4668: } elsif($string =~ /^__ARRAY_REF__/) {
4669: ($value, $string)=&str2arrayref($string);
4670: if($value->[0] eq 'Array reference error') {
4671: $hash{'error'}='Bad data';
4672: return (\%hash, $string);
4673: }
4674: } else {
4675: $value=&get_scalar(\$string,'__END_HASH_REF__');
4676: }
4677: $string =~ s/^&//;
4678:
4679: $hash{$key}=$value;
1.204 albertel 4680: }
1.265 albertel 4681:
4682: $string =~ s/^__END_HASH_REF__//;
4683:
4684: return (\%hash, $string);
1.204 albertel 4685: }
4686:
4687: sub str2array {
1.265 albertel 4688: my ($string)=@_;
4689: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4690: return @$array;
4691: }
4692:
4693: sub str2arrayref {
1.204 albertel 4694: my ($string) = @_;
1.265 albertel 4695: my @array;
4696:
4697: if($string !~ /^__ARRAY_REF__/) {
4698: if (! ($string eq '' || !defined($string))) {
4699: $array[0]='Array reference error';
4700: }
4701: return (\@array, $string);
4702: }
4703:
4704: $string =~ s/^__ARRAY_REF__//;
4705:
4706: while($string !~ /^__END_ARRAY_REF__/) {
4707: my $value='';
4708: if($string =~ /^__HASH_REF__/) {
4709: ($value, $string)=&str2hashref($string);
4710: if(defined($value->{'error'})) {
4711: $array[0] ='Array reference error';
4712: return (\@array, $string);
4713: }
4714: } elsif($string =~ /^__ARRAY_REF__/) {
4715: ($value, $string)=&str2arrayref($string);
4716: if($value->[0] eq 'Array reference error') {
4717: $array[0] ='Array reference error';
4718: return (\@array, $string);
4719: }
4720: } else {
4721: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4722: }
4723: $string =~ s/^&//;
4724:
4725: push(@array, $value);
1.191 harris41 4726: }
1.265 albertel 4727:
4728: $string =~ s/^__END_ARRAY_REF__//;
4729:
4730: return (\@array, $string);
1.168 albertel 4731: }
4732:
1.167 albertel 4733: # -------------------------------------------------------------------Temp Store
4734:
1.168 albertel 4735: sub tmpreset {
4736: my ($symb,$namespace,$domain,$stuname) = @_;
4737: if (!$symb) {
4738: $symb=&symbread();
1.620 albertel 4739: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4740: }
4741: $symb=escape($symb);
4742:
1.620 albertel 4743: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4744: $namespace=~s/\//\_/g;
4745: $namespace=~s/\W//g;
4746:
1.620 albertel 4747: if (!$domain) { $domain=$env{'user.domain'}; }
4748: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4749: if ($domain eq 'public' && $stuname eq 'public') {
4750: $stuname=$ENV{'REMOTE_ADDR'};
4751: }
1.1117 foxr 4752: my $path=LONCAPA::tempdir();
1.168 albertel 4753: my %hash;
4754: if (tie(%hash,'GDBM_File',
4755: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4756: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4757: foreach my $key (keys(%hash)) {
1.180 albertel 4758: if ($key=~ /:$symb/) {
1.168 albertel 4759: delete($hash{$key});
4760: }
4761: }
4762: }
4763: }
4764:
1.167 albertel 4765: sub tmpstore {
1.168 albertel 4766: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4767:
4768: if (!$symb) {
4769: $symb=&symbread();
1.620 albertel 4770: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4771: }
4772: $symb=escape($symb);
4773:
4774: if (!$namespace) {
4775: # I don't think we would ever want to store this for a course.
4776: # it seems this will only be used if we don't have a course.
1.620 albertel 4777: #$namespace=$env{'request.course.id'};
1.168 albertel 4778: #if (!$namespace) {
1.620 albertel 4779: $namespace=$env{'request.state'};
1.168 albertel 4780: #}
4781: }
4782: $namespace=~s/\//\_/g;
4783: $namespace=~s/\W//g;
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.168 albertel 4789: my $now=time;
4790: my %hash;
1.1117 foxr 4791: my $path=LONCAPA::tempdir();
1.168 albertel 4792: if (tie(%hash,'GDBM_File',
4793: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4794: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4795: $hash{"version:$symb"}++;
4796: my $version=$hash{"version:$symb"};
4797: my $allkeys='';
4798: foreach my $key (keys(%$storehash)) {
4799: $allkeys.=$key.':';
1.591 albertel 4800: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4801: }
4802: $hash{"$version:$symb:timestamp"}=$now;
4803: $allkeys.='timestamp';
4804: $hash{"$version:keys:$symb"}=$allkeys;
4805: if (untie(%hash)) {
4806: return 'ok';
4807: } else {
4808: return "error:$!";
4809: }
4810: } else {
4811: return "error:$!";
4812: }
4813: }
1.167 albertel 4814:
1.168 albertel 4815: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4816:
1.168 albertel 4817: sub tmprestore {
4818: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4819:
1.168 albertel 4820: if (!$symb) {
4821: $symb=&symbread();
1.620 albertel 4822: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4823: }
4824: $symb=escape($symb);
4825:
1.620 albertel 4826: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4827:
1.620 albertel 4828: if (!$domain) { $domain=$env{'user.domain'}; }
4829: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4830: if ($domain eq 'public' && $stuname eq 'public') {
4831: $stuname=$ENV{'REMOTE_ADDR'};
4832: }
1.168 albertel 4833: my %returnhash;
4834: $namespace=~s/\//\_/g;
4835: $namespace=~s/\W//g;
4836: my %hash;
1.1117 foxr 4837: my $path=LONCAPA::tempdir();
1.168 albertel 4838: if (tie(%hash,'GDBM_File',
4839: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4840: &GDBM_READER(),0640)) {
1.168 albertel 4841: my $version=$hash{"version:$symb"};
4842: $returnhash{'version'}=$version;
4843: my $scope;
4844: for ($scope=1;$scope<=$version;$scope++) {
4845: my $vkeys=$hash{"$scope:keys:$symb"};
4846: my @keys=split(/:/,$vkeys);
4847: my $key;
4848: $returnhash{"$scope:keys"}=$vkeys;
4849: foreach $key (@keys) {
1.591 albertel 4850: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4851: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4852: }
4853: }
1.168 albertel 4854: if (!(untie(%hash))) {
4855: return "error:$!";
4856: }
4857: } else {
4858: return "error:$!";
4859: }
4860: return %returnhash;
1.167 albertel 4861: }
4862:
1.9 www 4863: # ----------------------------------------------------------------------- Store
4864:
4865: sub store {
1.124 www 4866: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4867: my $home='';
4868:
1.168 albertel 4869: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4870:
1.213 www 4871: $symb=&symbclean($symb);
1.122 albertel 4872: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4873:
1.620 albertel 4874: if (!$domain) { $domain=$env{'user.domain'}; }
4875: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4876:
4877: &devalidate($symb,$stuname,$domain);
1.109 www 4878:
4879: $symb=escape($symb);
1.187 www 4880: if (!$namespace) {
1.620 albertel 4881: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4882: return '';
4883: }
4884: }
1.620 albertel 4885: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4886:
4887: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4888: $$storehash{'host'}=$perlvar{'lonHostID'};
4889:
1.12 www 4890: my $namevalue='';
1.800 albertel 4891: foreach my $key (keys(%$storehash)) {
4892: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4893: }
1.12 www 4894: $namevalue=~s/\&$//;
1.187 www 4895: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4896: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4897: }
4898:
1.47 www 4899: # -------------------------------------------------------------- Critical Store
4900:
4901: sub cstore {
1.124 www 4902: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4903: my $home='';
4904:
1.168 albertel 4905: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4906:
1.213 www 4907: $symb=&symbclean($symb);
1.122 albertel 4908: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4909:
1.620 albertel 4910: if (!$domain) { $domain=$env{'user.domain'}; }
4911: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4912:
4913: &devalidate($symb,$stuname,$domain);
1.109 www 4914:
4915: $symb=escape($symb);
1.187 www 4916: if (!$namespace) {
1.620 albertel 4917: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4918: return '';
4919: }
4920: }
1.620 albertel 4921: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4922:
4923: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4924: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4925:
1.47 www 4926: my $namevalue='';
1.800 albertel 4927: foreach my $key (keys(%$storehash)) {
4928: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4929: }
1.47 www 4930: $namevalue=~s/\&$//;
1.187 www 4931: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4932: return critical
4933: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4934: }
4935:
1.9 www 4936: # --------------------------------------------------------------------- Restore
4937:
4938: sub restore {
1.124 www 4939: my ($symb,$namespace,$domain,$stuname) = @_;
4940: my $home='';
4941:
1.168 albertel 4942: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4943:
1.122 albertel 4944: if (!$symb) {
1.1172.2.26 raeburn 4945: return if ($namespace eq 'courserequests');
4946: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4947: } else {
1.1172.2.26 raeburn 4948: unless ($namespace eq 'courserequests') {
4949: $symb=&escape(&symbclean($symb));
4950: }
1.122 albertel 4951: }
1.188 www 4952: if (!$namespace) {
1.620 albertel 4953: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4954: return '';
4955: }
4956: }
1.620 albertel 4957: if (!$domain) { $domain=$env{'user.domain'}; }
4958: if (!$stuname) { $stuname=$env{'user.name'}; }
4959: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4960: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4961:
1.12 www 4962: my %returnhash=();
1.800 albertel 4963: foreach my $line (split(/\&/,$answer)) {
4964: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4965: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4966: }
1.75 www 4967: my $version;
4968: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4969: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4970: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4971: }
1.75 www 4972: }
1.13 www 4973: return %returnhash;
1.34 www 4974: }
4975:
4976: # ---------------------------------------------------------- Course Description
1.1118 foxr 4977: #
4978: #
1.34 www 4979:
4980: sub coursedescription {
1.731 albertel 4981: my ($courseid,$args)=@_;
1.34 www 4982: $courseid=~s/^\///;
1.49 www 4983: $courseid=~s/\_/\//g;
1.34 www 4984: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4985: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4986: my $normalid=$cdomain.'_'.$cnum;
4987: # need to always cache even if we get errors otherwise we keep
4988: # trying and trying and trying to get the course description.
4989: my %envhash=();
4990: my %returnhash=();
1.731 albertel 4991:
4992: my $expiretime=600;
4993: if ($env{'request.course.id'} eq $normalid) {
4994: $expiretime=120;
4995: }
4996:
4997: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4998: if (!$args->{'freshen_cache'}
4999: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5000: foreach my $key (keys(%env)) {
5001: next if ($key !~ /^\Q$prefix\E(.*)/);
5002: my ($setting) = $1;
5003: $returnhash{$setting} = $env{$key};
5004: }
5005: return %returnhash;
5006: }
5007:
1.1118 foxr 5008: # get the data again
5009:
1.731 albertel 5010: if (!$args->{'one_time'}) {
5011: $envhash{'course.'.$normalid.'.last_cache'}=time;
5012: }
1.811 albertel 5013:
1.34 www 5014: if ($chome ne 'no_host') {
1.302 albertel 5015: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5016: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5017: my $username = $env{'user.name'}; # Defult username
5018: if(defined $args->{'user'}) {
5019: $username = $args->{'user'};
5020: }
1.129 albertel 5021: $returnhash{'home'}= $chome;
5022: $returnhash{'domain'} = $cdomain;
5023: $returnhash{'num'} = $cnum;
1.741 raeburn 5024: if (!defined($returnhash{'type'})) {
5025: $returnhash{'type'} = 'Course';
5026: }
1.130 albertel 5027: while (my ($name,$value) = each %returnhash) {
1.53 www 5028: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5029: }
1.270 www 5030: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5031: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5032: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5033: $envhash{'course.'.$normalid.'.home'}=$chome;
5034: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5035: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5036: }
5037: }
1.731 albertel 5038: if (!$args->{'one_time'}) {
1.949 raeburn 5039: &appenv(\%envhash);
1.731 albertel 5040: }
1.302 albertel 5041: return %returnhash;
1.461 www 5042: }
5043:
1.1080 raeburn 5044: sub update_released_required {
5045: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5046: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5047: $cid = $env{'request.course.id'};
5048: $cdom = $env{'course.'.$cid.'.domain'};
5049: $cnum = $env{'course.'.$cid.'.num'};
5050: $chome = $env{'course.'.$cid.'.home'};
5051: }
5052: if ($needsrelease) {
5053: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5054: my $needsupdate;
5055: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5056: $needsupdate = 1;
5057: } else {
5058: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5059: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5060: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5061: $needsupdate = 1;
5062: }
5063: }
5064: if ($needsupdate) {
5065: my %needshash = (
5066: 'internal.releaserequired' => $needsrelease,
5067: );
5068: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5069: if ($putresult eq 'ok') {
5070: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5071: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5072: if (ref($crsinfo{$cid}) eq 'HASH') {
5073: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5074: &courseidput($cdom,\%crsinfo,$chome,'notime');
5075: }
5076: }
5077: }
5078: }
5079: return;
5080: }
5081:
1.461 www 5082: # -------------------------------------------------See if a user is privileged
5083:
5084: sub privileged {
1.1172.2.23 raeburn 5085: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5086: my $now = time;
1.1172.2.23 raeburn 5087: my $roles;
5088: if (ref($possroles) eq 'ARRAY') {
5089: $roles = $possroles;
5090: } else {
5091: $roles = ['dc','su'];
5092: }
5093: if (ref($possdomains) eq 'ARRAY') {
5094: my %privileged = &privileged_by_domain($possdomains,$roles);
5095: foreach my $dom (@{$possdomains}) {
5096: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5097: (ref($privileged{$dom}) eq 'HASH')) {
5098: foreach my $role (@{$roles}) {
5099: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5100: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5101: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5102: return 1 unless (($end && $end < $now) ||
5103: ($start && $start > $now));
5104: }
5105: }
5106: }
5107: }
5108: }
5109: } else {
5110: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5111: my $now = time;
1.1170 droeschl 5112:
1.1172.2.23 raeburn 5113: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170 droeschl 5114: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5115: if (grep(/^\Q$trole\E$/,@{$roles})) {
5116: return 1 unless ($tend && $tend < $now)
5117: or ($tstart && $tstart > $now);
1.1170 droeschl 5118: }
1.1172.2.23 raeburn 5119: }
5120: }
1.461 www 5121: return 0;
1.9 www 5122: }
1.1 albertel 5123:
1.1172.2.23 raeburn 5124: sub privileged_by_domain {
5125: my ($domains,$roles) = @_;
5126: my %privileged = ();
5127: my $cachetime = 60*60*24;
5128: my $now = time;
5129: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5130: return %privileged;
5131: }
5132: foreach my $dom (@{$domains}) {
5133: next if (ref($privileged{$dom}) eq 'HASH');
5134: my $needroles;
5135: foreach my $role (@{$roles}) {
5136: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5137: if (defined($cached)) {
5138: if (ref($result) eq 'HASH') {
5139: $privileged{$dom}{$role} = $result;
5140: }
5141: } else {
5142: $needroles = 1;
5143: }
5144: }
5145: if ($needroles) {
5146: my %dompersonnel = &get_domain_roles($dom,$roles);
5147: $privileged{$dom} = {};
5148: foreach my $server (keys(%dompersonnel)) {
5149: if (ref($dompersonnel{$server}) eq 'HASH') {
5150: foreach my $item (keys(%{$dompersonnel{$server}})) {
5151: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5152: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5153: next if ($end && $end < $now);
5154: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5155: $dompersonnel{$server}{$item};
5156: }
5157: }
5158: }
5159: if (ref($privileged{$dom}) eq 'HASH') {
5160: foreach my $role (@{$roles}) {
5161: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5162: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5163: } else {
5164: my %hash = ();
5165: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5166: }
5167: }
5168: }
5169: }
5170: }
5171: return %privileged;
5172: }
5173:
1.103 harris41 5174: # -------------------------------------------------------- Get user privileges
1.11 www 5175:
5176: sub rolesinit {
1.1169 droeschl 5177: my ($domain, $username) = @_;
5178: my %userroles = ('user.login.time' => time);
5179: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5180:
5181: # firstaccess and timerinterval are related to timed maps/resources.
5182: # also, blocking can be triggered by an activating timer
5183: # it's saved in the user's %env.
5184: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5185: my %timerinterval = &dump('timerinterval', $domain, $username);
5186: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5187: %timerintchk, %timerintenv);
5188:
1.1162 raeburn 5189: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5190: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5191: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5192: }
1.1169 droeschl 5193:
1.1162 raeburn 5194: foreach my $key (keys(%timerinterval)) {
5195: my ($cid,$rest) = split(/\0/,$key);
5196: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5197: }
1.1169 droeschl 5198:
1.11 www 5199: my %allroles=();
1.1162 raeburn 5200: my %allgroups=();
1.11 www 5201:
1.1169 droeschl 5202: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5203: my $role = $rolesdump{$area};
5204: $area =~ s/\_\w\w$//;
5205:
5206: my ($trole, $tend, $tstart, $group_privs);
5207:
5208: if ($role =~ /^cr/) {
5209: # Custom role, defined by a user
5210: # e.g., user.role.cr/msu/smith/mynewrole
5211: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5212: $trole = $1;
5213: ($tend, $tstart) = split('_', $2);
5214: } else {
5215: $trole = $role;
5216: }
5217: } elsif ($role =~ m|^gr/|) {
5218: # Role of member in a group, defined within a course/community
5219: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5220: ($trole, $tend, $tstart) = split(/_/, $role);
5221: next if $tstart eq '-1';
5222: ($trole, $group_privs) = split(/\//, $trole);
5223: $group_privs = &unescape($group_privs);
5224: } else {
5225: # Just a normal role, defined in roles.tab
5226: ($trole, $tend, $tstart) = split(/_/,$role);
5227: }
5228:
5229: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5230: $username);
5231: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5232:
5233: # role expired or not available yet?
5234: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5235: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5236:
5237: next if $area eq '' or $trole eq '';
5238:
5239: my $spec = "$trole.$area";
5240: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5241:
5242: if ($trole =~ /^cr\//) {
5243: # Custom role, defined by a user
5244: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5245: } elsif ($trole eq 'gr') {
5246: # Role of a member in a group, defined within a course/community
5247: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5248: next;
5249: } else {
5250: # Normal role, defined in roles.tab
5251: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5252: }
5253:
5254: my $cid = $tdomain.'_'.$trest;
5255: unless ($firstaccchk{$cid}) {
5256: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5257: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5258: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5259: $coursetimerstarts{$cid}{$item};
5260: }
5261: }
5262: $firstaccchk{$cid} = 1;
5263: }
5264: unless ($timerintchk{$cid}) {
5265: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5266: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5267: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5268: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5269: }
1.12 www 5270: }
1.1169 droeschl 5271: $timerintchk{$cid} = 1;
1.191 harris41 5272: }
1.11 www 5273: }
1.1169 droeschl 5274:
5275: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5276: \%allroles, \%allgroups);
5277: $env{'user.adv'} = $userroles{'user.adv'};
5278:
1.1162 raeburn 5279: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5280: }
5281:
1.567 raeburn 5282: sub set_arearole {
1.1172.2.19 raeburn 5283: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5284: unless ($nolog) {
1.567 raeburn 5285: # log the associated role with the area
1.1172.2.19 raeburn 5286: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5287: }
1.743 albertel 5288: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5289: }
5290:
5291: sub custom_roleprivs {
5292: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5293: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40! raeburn 5294: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5295: if (&hostname($homsvr) ne '') {
1.567 raeburn 5296: my ($rdummy,$roledef)=
5297: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5298: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5299: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5300: if (defined($syspriv)) {
1.1043 raeburn 5301: if ($trest =~ /^$match_community$/) {
5302: $syspriv =~ s/bre\&S//;
5303: }
1.567 raeburn 5304: $$allroles{'cm./'}.=':'.$syspriv;
5305: $$allroles{$spec.'./'}.=':'.$syspriv;
5306: }
5307: if ($tdomain ne '') {
5308: if (defined($dompriv)) {
5309: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5310: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5311: }
5312: if (($trest ne '') && (defined($coursepriv))) {
5313: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5314: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5315: }
5316: }
5317: }
5318: }
5319: }
5320:
1.678 raeburn 5321: sub group_roleprivs {
5322: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5323: my $access = 1;
5324: my $now = time;
5325: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5326: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5327: if ($access) {
1.811 albertel 5328: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5329: $$allgroups{$course}{$group} .=':'.$group_privs;
5330: }
5331: }
1.567 raeburn 5332:
5333: sub standard_roleprivs {
5334: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5335: if (defined($pr{$trole.':s'})) {
5336: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5337: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5338: }
5339: if ($tdomain ne '') {
5340: if (defined($pr{$trole.':d'})) {
5341: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5342: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5343: }
5344: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5345: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5346: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5347: }
5348: }
5349: }
5350:
5351: sub set_userprivs {
1.1064 raeburn 5352: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5353: my $author=0;
5354: my $adv=0;
1.678 raeburn 5355: my %grouproles = ();
5356: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5357: my @groupkeys;
1.1000 raeburn 5358: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5359: push(@groupkeys,$role);
5360: }
5361: if (ref($groups_roles) eq 'HASH') {
5362: foreach my $key (keys(%{$groups_roles})) {
5363: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5364: push(@groupkeys,$key);
5365: }
5366: }
5367: }
5368: if (@groupkeys > 0) {
5369: foreach my $role (@groupkeys) {
5370: my ($trole,$area,$sec,$extendedarea);
5371: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5372: $trole = $1;
5373: $area = $2;
5374: $sec = $3;
5375: $extendedarea = $area.$sec;
5376: if (exists($$allgroups{$area})) {
5377: foreach my $group (keys(%{$$allgroups{$area}})) {
5378: my $spec = $trole.'.'.$extendedarea;
5379: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5380: $$allgroups{$area}{$group};
1.1064 raeburn 5381: }
1.678 raeburn 5382: }
5383: }
5384: }
5385: }
5386: }
1.800 albertel 5387: foreach my $group (keys(%grouproles)) {
5388: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5389: }
1.800 albertel 5390: foreach my $role (keys(%{$allroles})) {
5391: my %thesepriv;
1.941 raeburn 5392: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5393: foreach my $item (split(/:/,$$allroles{$role})) {
5394: if ($item ne '') {
5395: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5396: if ($restrictions eq '') {
5397: $thesepriv{$privilege}='F';
5398: } elsif ($thesepriv{$privilege} ne 'F') {
5399: $thesepriv{$privilege}.=$restrictions;
5400: }
5401: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5402: }
5403: }
5404: my $thesestr='';
1.1104 raeburn 5405: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5406: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5407: }
5408: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5409: }
5410: return ($author,$adv);
5411: }
5412:
1.994 raeburn 5413: sub role_status {
1.1104 raeburn 5414: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5415: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40! raeburn 5416: my ($one,$two) = split(m{\./},$rolekey,2);
! 5417: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5418: unless (!defined($$role) || $$role eq '') {
1.1172.2.40! raeburn 5419: $$where = '/'.$two;
1.994 raeburn 5420: $$trolecode=$$role.'.'.$$where;
5421: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5422: $$tstatus='is';
1.1104 raeburn 5423: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5424: $$tstatus='future';
1.1034 raeburn 5425: if ($$tstart<$now) {
5426: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5427: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5428: my (%allroles,%allgroups,$group_privs,
5429: %groups_roles,@rolecodes);
1.1002 raeburn 5430: my %userroles = (
5431: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5432: );
1.1064 raeburn 5433: @rolecodes = ('cm');
1.1002 raeburn 5434: my $spec=$$role.'.'.$$where;
5435: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5436: if ($$role =~ /^cr\//) {
5437: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5438: push(@rolecodes,'cr');
1.1002 raeburn 5439: } elsif ($$role eq 'gr') {
1.1064 raeburn 5440: push(@rolecodes,$$role);
1.1002 raeburn 5441: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5442: $env{'user.name'});
1.1064 raeburn 5443: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5444: (undef,my $group_privs) = split(/\//,$trole);
5445: $group_privs = &unescape($group_privs);
5446: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5447: 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 5448: &get_groups_roles($tdomain,$trest,
5449: \%course_roles,\@rolecodes,
5450: \%groups_roles);
1.1002 raeburn 5451: } else {
1.1064 raeburn 5452: push(@rolecodes,$$role);
1.1002 raeburn 5453: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5454: }
1.1064 raeburn 5455: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5456: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5457: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5458: }
5459: }
1.1034 raeburn 5460: $$tstatus = 'is';
1.1002 raeburn 5461: }
1.994 raeburn 5462: }
5463: if ($$tend) {
1.1104 raeburn 5464: if ($$tend<$update) {
1.994 raeburn 5465: $$tstatus='expired';
5466: } elsif ($$tend<$now) {
5467: $$tstatus='will_not';
5468: }
5469: }
5470: }
5471: }
5472: }
5473:
1.1104 raeburn 5474: sub get_groups_roles {
5475: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5476: return unless((ref($cdom_courseroles) eq 'HASH') &&
5477: (ref($rolecodes) eq 'ARRAY') &&
5478: (ref($groups_roles) eq 'HASH'));
5479: if (keys(%{$cdom_courseroles}) > 0) {
5480: my ($cnum) = ($rest =~ /^($match_courseid)/);
5481: if ($cdom ne '' && $cnum ne '') {
5482: foreach my $key (keys(%{$cdom_courseroles})) {
5483: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5484: my $crsrole = $1;
5485: my $crssec = $2;
5486: if ($crsrole =~ /^cr/) {
5487: unless (grep(/^cr$/,@{$rolecodes})) {
5488: push(@{$rolecodes},'cr');
5489: }
5490: } else {
5491: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5492: push(@{$rolecodes},$crsrole);
5493: }
5494: }
5495: my $rolekey = "$crsrole./$cdom/$cnum";
5496: if ($crssec ne '') {
5497: $rolekey .= "/$crssec";
5498: }
5499: $rolekey .= './';
5500: $groups_roles->{$rolekey} = $rolecodes;
5501: }
5502: }
5503: }
5504: }
5505: return;
5506: }
5507:
5508: sub delete_env_groupprivs {
5509: my ($where,$courseroles,$possroles) = @_;
5510: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5511: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5512: unless (ref($courseroles->{$udom}) eq 'HASH') {
5513: %{$courseroles->{$udom}} =
5514: &get_my_roles('','','userroles',['active'],
5515: $possroles,[$udom],1);
5516: }
5517: if (ref($courseroles->{$udom}) eq 'HASH') {
5518: foreach my $item (keys(%{$courseroles->{$udom}})) {
5519: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5520: my $area = '/'.$cdom.'/'.$cnum;
5521: my $privkey = "user.priv.$crsrole.$area";
5522: if ($crssec ne '') {
5523: $privkey .= '/'.$crssec;
5524: }
5525: $privkey .= ".$area/$group";
5526: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5527: }
5528: }
5529: return;
5530: }
5531:
1.994 raeburn 5532: sub check_adhoc_privs {
1.1104 raeburn 5533: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5534: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9 raeburn 5535: my $setprivs;
1.994 raeburn 5536: if ($env{$cckey}) {
5537: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5538: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5539: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5540: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5541: $setprivs = 1;
1.994 raeburn 5542: }
5543: } else {
1.1088 raeburn 5544: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5545: $setprivs = 1;
1.994 raeburn 5546: }
1.1172.2.9 raeburn 5547: return $setprivs;
1.994 raeburn 5548: }
5549:
5550: sub set_adhoc_privileges {
5551: # role can be cc or ca
1.1088 raeburn 5552: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5553: my $area = '/'.$dcdom.'/'.$pickedcourse;
5554: my $spec = $role.'.'.$area;
5555: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 5556: $env{'user.name'},1);
1.994 raeburn 5557: my %ccrole = ();
5558: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5559: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5560: &appenv(\%userroles,[$role,'cm']);
5561: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5562: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5563: &appenv( {'request.role' => $spec,
5564: 'request.role.domain' => $dcdom,
5565: 'request.course.sec' => ''
5566: }
5567: );
5568: my $tadv=0;
5569: if (&allowed('adv') eq 'F') { $tadv=1; }
5570: &appenv({'request.role.adv' => $tadv});
5571: }
1.994 raeburn 5572: }
5573:
1.12 www 5574: # --------------------------------------------------------------- get interface
5575:
5576: sub get {
1.131 albertel 5577: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5578: my $items='';
1.800 albertel 5579: foreach my $item (@$storearr) {
5580: $items.=&escape($item).'&';
1.191 harris41 5581: }
1.12 www 5582: $items=~s/\&$//;
1.620 albertel 5583: if (!$udomain) { $udomain=$env{'user.domain'}; }
5584: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5585: my $uhome=&homeserver($uname,$udomain);
5586:
1.133 albertel 5587: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5588: my @pairs=split(/\&/,$rep);
1.273 albertel 5589: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5590: return @pairs;
5591: }
1.15 www 5592: my %returnhash=();
1.42 www 5593: my $i=0;
1.800 albertel 5594: foreach my $item (@$storearr) {
5595: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5596: $i++;
1.191 harris41 5597: }
1.15 www 5598: return %returnhash;
1.27 www 5599: }
5600:
5601: # --------------------------------------------------------------- del interface
5602:
5603: sub del {
1.133 albertel 5604: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5605: my $items='';
1.800 albertel 5606: foreach my $item (@$storearr) {
5607: $items.=&escape($item).'&';
1.191 harris41 5608: }
1.984 neumanie 5609:
1.27 www 5610: $items=~s/\&$//;
1.620 albertel 5611: if (!$udomain) { $udomain=$env{'user.domain'}; }
5612: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5613: my $uhome=&homeserver($uname,$udomain);
5614: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5615: }
5616:
5617: # -------------------------------------------------------------- dump interface
5618:
1.1172.2.22 raeburn 5619: sub unserialize {
5620: my ($rep, $escapedkeys) = @_;
5621:
5622: return {} if $rep =~ /^error/;
5623:
5624: my %returnhash=();
5625: foreach my $item (split(/\&/,$rep)) {
5626: my ($key, $value) = split(/=/, $item, 2);
5627: $key = unescape($key) unless $escapedkeys;
5628: next if $key =~ /^error: 2 /;
5629: $returnhash{$key} = &thaw_unescape($value);
5630: }
5631: return \%returnhash;
5632: }
5633:
5634: # see Lond::dump_with_regexp
5635: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5636: sub dump {
1.1172.2.22 raeburn 5637: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5638: if (!$udomain) { $udomain=$env{'user.domain'}; }
5639: if (!$uname) { $uname=$env{'user.name'}; }
5640: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5641:
1.1172.2.22 raeburn 5642: my $reply;
5643: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
5644: # user is hosted on this machine
5645: $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 5646: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 5647: return %{&unserialize($reply, $escapedkeys)};
5648: }
1.755 albertel 5649: if ($regexp) {
5650: $regexp=&escape($regexp);
5651: } else {
5652: $regexp='.';
5653: }
1.1166 raeburn 5654: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5655: my @pairs=split(/\&/,$rep);
5656: my %returnhash=();
1.1098 foxr 5657: if (!($rep =~ /^error/ )) {
5658: foreach my $item (@pairs) {
5659: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 5660: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 5661: next if ($key =~ /^error: 2 /);
5662: $returnhash{$key}=&thaw_unescape($value);
5663: }
1.755 albertel 5664: }
5665: return %returnhash;
1.407 www 5666: }
5667:
1.1098 foxr 5668:
1.717 albertel 5669: # --------------------------------------------------------- dumpstore interface
5670:
5671: sub dumpstore {
5672: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 5673: # same as dump but keys must be escaped. They may contain colon separated
5674: # lists of values that may themself contain colons (e.g. symbs).
5675: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5676: }
5677:
1.407 www 5678: # -------------------------------------------------------------- keys interface
5679:
5680: sub getkeys {
5681: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5682: if (!$udomain) { $udomain=$env{'user.domain'}; }
5683: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5684: my $uhome=&homeserver($uname,$udomain);
5685: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5686: my @keyarray=();
1.800 albertel 5687: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5688: next if ($key =~ /^error: 2 /);
1.800 albertel 5689: push(@keyarray,&unescape($key));
1.407 www 5690: }
5691: return @keyarray;
1.318 matthew 5692: }
5693:
1.319 matthew 5694: # --------------------------------------------------------------- currentdump
5695: sub currentdump {
1.328 matthew 5696: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5697: $courseid = $env{'request.course.id'} if (! defined($courseid));
5698: $sdom = $env{'user.domain'} if (! defined($sdom));
5699: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5700: my $uhome = &homeserver($sname,$sdom);
5701: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 5702: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5703: #
1.318 matthew 5704: my %returnhash=();
1.319 matthew 5705: #
5706: if ($rep eq "unknown_cmd") {
5707: # an old lond will not know currentdump
5708: # Do a dump and make it look like a currentdump
1.822 albertel 5709: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5710: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5711: my %hash = @tmp;
5712: @tmp=();
1.424 matthew 5713: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5714: } else {
5715: my @pairs=split(/\&/,$rep);
1.800 albertel 5716: foreach my $pair (@pairs) {
5717: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5718: my ($symb,$param) = split(/:/,$key);
5719: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5720: &thaw_unescape($value);
1.319 matthew 5721: }
1.191 harris41 5722: }
1.12 www 5723: return %returnhash;
1.424 matthew 5724: }
5725:
5726: sub convert_dump_to_currentdump{
5727: my %hash = %{shift()};
5728: my %returnhash;
5729: # Code ripped from lond, essentially. The only difference
5730: # here is the unescaping done by lonnet::dump(). Conceivably
5731: # we might run in to problems with parameter names =~ /^v\./
5732: while (my ($key,$value) = each(%hash)) {
5733: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5734: $symb = &unescape($symb);
5735: $param = &unescape($param);
1.424 matthew 5736: next if ($v eq 'version' || $symb eq 'keys');
5737: next if (exists($returnhash{$symb}) &&
5738: exists($returnhash{$symb}->{$param}) &&
5739: $returnhash{$symb}->{'v.'.$param} > $v);
5740: $returnhash{$symb}->{$param}=$value;
5741: $returnhash{$symb}->{'v.'.$param}=$v;
5742: }
5743: #
5744: # Remove all of the keys in the hashes which keep track of
5745: # the version of the parameter.
5746: while (my ($symb,$param_hash) = each(%returnhash)) {
5747: # use a foreach because we are going to delete from the hash.
5748: foreach my $key (keys(%$param_hash)) {
5749: delete($param_hash->{$key}) if ($key =~ /^v\./);
5750: }
5751: }
5752: return \%returnhash;
1.12 www 5753: }
5754:
1.627 albertel 5755: # ------------------------------------------------------ critical inc interface
5756:
5757: sub cinc {
5758: return &inc(@_,'critical');
5759: }
5760:
1.449 matthew 5761: # --------------------------------------------------------------- inc interface
5762:
5763: sub inc {
1.627 albertel 5764: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5765: if (!$udomain) { $udomain=$env{'user.domain'}; }
5766: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5767: my $uhome=&homeserver($uname,$udomain);
5768: my $items='';
5769: if (! ref($store)) {
5770: # got a single value, so use that instead
5771: $items = &escape($store).'=&';
5772: } elsif (ref($store) eq 'SCALAR') {
5773: $items = &escape($$store).'=&';
5774: } elsif (ref($store) eq 'ARRAY') {
5775: $items = join('=&',map {&escape($_);} @{$store});
5776: } elsif (ref($store) eq 'HASH') {
5777: while (my($key,$value) = each(%{$store})) {
5778: $items.= &escape($key).'='.&escape($value).'&';
5779: }
5780: }
5781: $items=~s/\&$//;
1.627 albertel 5782: if ($critical) {
5783: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5784: } else {
5785: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5786: }
1.449 matthew 5787: }
5788:
1.12 www 5789: # --------------------------------------------------------------- put interface
5790:
5791: sub put {
1.134 albertel 5792: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5793: if (!$udomain) { $udomain=$env{'user.domain'}; }
5794: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5795: my $uhome=&homeserver($uname,$udomain);
1.12 www 5796: my $items='';
1.800 albertel 5797: foreach my $item (keys(%$storehash)) {
5798: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5799: }
1.12 www 5800: $items=~s/\&$//;
1.134 albertel 5801: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5802: }
5803:
1.631 albertel 5804: # ------------------------------------------------------------ newput interface
5805:
5806: sub newput {
5807: my ($namespace,$storehash,$udomain,$uname)=@_;
5808: if (!$udomain) { $udomain=$env{'user.domain'}; }
5809: if (!$uname) { $uname=$env{'user.name'}; }
5810: my $uhome=&homeserver($uname,$udomain);
5811: my $items='';
5812: foreach my $key (keys(%$storehash)) {
5813: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5814: }
5815: $items=~s/\&$//;
5816: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5817: }
5818:
5819: # --------------------------------------------------------- putstore interface
5820:
1.524 raeburn 5821: sub putstore {
1.715 albertel 5822: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5823: if (!$udomain) { $udomain=$env{'user.domain'}; }
5824: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5825: my $uhome=&homeserver($uname,$udomain);
5826: my $items='';
1.715 albertel 5827: foreach my $key (keys(%$storehash)) {
5828: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5829: }
1.715 albertel 5830: $items=~s/\&$//;
1.716 albertel 5831: my $esc_symb=&escape($symb);
5832: my $esc_v=&escape($version);
1.715 albertel 5833: my $reply =
1.716 albertel 5834: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5835: $uhome);
5836: if ($reply eq 'unknown_cmd') {
1.716 albertel 5837: # gfall back to way things use to be done
1.715 albertel 5838: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5839: $uname);
1.524 raeburn 5840: }
1.715 albertel 5841: return $reply;
5842: }
5843:
5844: sub old_putstore {
1.716 albertel 5845: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5846: if (!$udomain) { $udomain=$env{'user.domain'}; }
5847: if (!$uname) { $uname=$env{'user.name'}; }
5848: my $uhome=&homeserver($uname,$udomain);
5849: my %newstorehash;
1.800 albertel 5850: foreach my $item (keys(%$storehash)) {
5851: my $key = $version.':'.&escape($symb).':'.$item;
5852: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5853: }
5854: my $items='';
5855: my %allitems = ();
1.800 albertel 5856: foreach my $item (keys(%newstorehash)) {
5857: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5858: my $key = $1.':keys:'.$2;
5859: $allitems{$key} .= $3.':';
5860: }
1.800 albertel 5861: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5862: }
1.800 albertel 5863: foreach my $item (keys(%allitems)) {
5864: $allitems{$item} =~ s/\:$//;
5865: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5866: }
5867: $items=~s/\&$//;
5868: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5869: }
5870:
1.47 www 5871: # ------------------------------------------------------ critical put interface
5872:
5873: sub cput {
1.134 albertel 5874: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5875: if (!$udomain) { $udomain=$env{'user.domain'}; }
5876: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5877: my $uhome=&homeserver($uname,$udomain);
1.47 www 5878: my $items='';
1.800 albertel 5879: foreach my $item (keys(%$storehash)) {
5880: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5881: }
1.47 www 5882: $items=~s/\&$//;
1.134 albertel 5883: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5884: }
5885:
5886: # -------------------------------------------------------------- eget interface
5887:
5888: sub eget {
1.133 albertel 5889: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5890: my $items='';
1.800 albertel 5891: foreach my $item (@$storearr) {
5892: $items.=&escape($item).'&';
1.191 harris41 5893: }
1.12 www 5894: $items=~s/\&$//;
1.620 albertel 5895: if (!$udomain) { $udomain=$env{'user.domain'}; }
5896: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5897: my $uhome=&homeserver($uname,$udomain);
5898: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5899: my @pairs=split(/\&/,$rep);
5900: my %returnhash=();
1.42 www 5901: my $i=0;
1.800 albertel 5902: foreach my $item (@$storearr) {
5903: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5904: $i++;
1.191 harris41 5905: }
1.12 www 5906: return %returnhash;
5907: }
5908:
1.667 albertel 5909: # ------------------------------------------------------------ tmpput interface
5910: sub tmpput {
1.802 raeburn 5911: my ($storehash,$server,$context)=@_;
1.667 albertel 5912: my $items='';
1.800 albertel 5913: foreach my $item (keys(%$storehash)) {
5914: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5915: }
5916: $items=~s/\&$//;
1.802 raeburn 5917: if (defined($context)) {
5918: $items .= ':'.&escape($context);
5919: }
1.667 albertel 5920: return &reply("tmpput:$items",$server);
5921: }
5922:
5923: # ------------------------------------------------------------ tmpget interface
5924: sub tmpget {
1.688 albertel 5925: my ($token,$server)=@_;
5926: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5927: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5928: my %returnhash;
5929: foreach my $item (split(/\&/,$rep)) {
5930: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5931: next if ($key =~ /^error: 2 /);
1.667 albertel 5932: $returnhash{&unescape($key)}=&thaw_unescape($value);
5933: }
5934: return %returnhash;
5935: }
5936:
1.1113 raeburn 5937: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5938: sub tmpdel {
5939: my ($token,$server)=@_;
5940: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5941: return &reply("tmpdel:$token",$server);
5942: }
5943:
1.1172.2.13 raeburn 5944: # ------------------------------------------------------------ get_timebased_id
5945:
5946: sub get_timebased_id {
5947: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5948: $maxtries) = @_;
5949: my ($newid,$error,$dellock);
5950: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5951: return ('','ok','invalid call to get suffix');
5952: }
5953:
5954: # set defaults for any optional args for which values were not supplied
5955: if ($who eq '') {
5956: $who = $env{'user.name'}.':'.$env{'user.domain'};
5957: }
5958: if (!$locktries) {
5959: $locktries = 3;
5960: }
5961: if (!$maxtries) {
5962: $maxtries = 10;
5963: }
5964:
5965: if (($cdom eq '') || ($cnum eq '')) {
5966: if ($env{'request.course.id'}) {
5967: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5968: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5969: }
5970: if (($cdom eq '') || ($cnum eq '')) {
5971: return ('','ok','call to get suffix not in course context');
5972: }
5973: }
5974:
5975: # construct locking item
5976: my $lockhash = {
5977: $prefix."\0".'locked_'.$keyid => $who,
5978: };
5979: my $tries = 0;
5980:
5981: # attempt to get lock on nohist_$namespace file
5982: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5983: while (($gotlock ne 'ok') && $tries <$locktries) {
5984: $tries ++;
5985: sleep 1;
5986: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5987: }
5988:
5989: # attempt to get unique identifier, based on current timestamp
5990: if ($gotlock eq 'ok') {
5991: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
5992: my $id = time;
5993: $newid = $id;
5994: my $idtries = 0;
5995: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
5996: if ($idtype eq 'concat') {
5997: $newid = $id.$idtries;
5998: } else {
5999: $newid ++;
6000: }
6001: $idtries ++;
6002: }
6003: if (!exists($inuse{$prefix."\0".$newid})) {
6004: my %new_item = (
6005: $prefix."\0".$newid => $who,
6006: );
6007: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6008: $cdom,$cnum);
6009: if ($putresult ne 'ok') {
6010: undef($newid);
6011: $error = 'error saving new item: '.$putresult;
6012: }
6013: } else {
6014: $error = ('error: no unique suffix available for the new item ');
6015: }
6016: # remove lock
6017: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6018: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6019: } else {
6020: $error = "error: could not obtain lockfile\n";
6021: $dellock = 'ok';
6022: }
6023: return ($newid,$dellock,$error);
6024: }
6025:
1.765 albertel 6026: # -------------------------------------------------- portfolio access checking
6027:
6028: sub portfolio_access {
1.766 albertel 6029: my ($requrl) = @_;
1.765 albertel 6030: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6031: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 6032: if ($result) {
6033: my %setters;
6034: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6035: my ($startblock,$endblock) =
6036: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6037: if ($startblock && $endblock) {
6038: return 'B';
6039: }
6040: } else {
6041: my ($startblock,$endblock) =
6042: &Apache::loncommon::blockcheck(\%setters,'port');
6043: if ($startblock && $endblock) {
6044: return 'B';
6045: }
6046: }
6047: }
1.765 albertel 6048: if ($result eq 'ok') {
1.766 albertel 6049: return 'F';
1.765 albertel 6050: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6051: return 'A';
1.765 albertel 6052: }
1.766 albertel 6053: return '';
1.765 albertel 6054: }
6055:
6056: sub get_portfolio_access {
1.767 albertel 6057: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
6058:
6059: if (!ref($access_hash)) {
6060: my $current_perms = &get_portfile_permissions($udom,$unum);
6061: my %access_controls = &get_access_controls($current_perms,$group,
6062: $file_name);
6063: $access_hash = $access_controls{$file_name};
6064: }
6065:
1.765 albertel 6066: my ($public,$guest,@domains,@users,@courses,@groups);
6067: my $now = time;
6068: if (ref($access_hash) eq 'HASH') {
6069: foreach my $key (keys(%{$access_hash})) {
6070: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6071: if ($start > $now) {
6072: next;
6073: }
6074: if ($end && $end<$now) {
6075: next;
6076: }
6077: if ($scope eq 'public') {
6078: $public = $key;
6079: last;
6080: } elsif ($scope eq 'guest') {
6081: $guest = $key;
6082: } elsif ($scope eq 'domains') {
6083: push(@domains,$key);
6084: } elsif ($scope eq 'users') {
6085: push(@users,$key);
6086: } elsif ($scope eq 'course') {
6087: push(@courses,$key);
6088: } elsif ($scope eq 'group') {
6089: push(@groups,$key);
6090: }
6091: }
6092: if ($public) {
6093: return 'ok';
6094: }
6095: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6096: if ($guest) {
6097: return $guest;
6098: }
6099: } else {
6100: if (@domains > 0) {
6101: foreach my $domkey (@domains) {
6102: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6103: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6104: return 'ok';
6105: }
6106: }
6107: }
6108: }
6109: if (@users > 0) {
6110: foreach my $userkey (@users) {
1.865 raeburn 6111: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6112: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6113: if (ref($item) eq 'HASH') {
6114: if (($item->{'uname'} eq $env{'user.name'}) &&
6115: ($item->{'udom'} eq $env{'user.domain'})) {
6116: return 'ok';
6117: }
6118: }
6119: }
6120: }
1.765 albertel 6121: }
6122: }
6123: my %roleshash;
6124: my @courses_and_groups = @courses;
6125: push(@courses_and_groups,@groups);
6126: if (@courses_and_groups > 0) {
6127: my (%allgroups,%allroles);
6128: my ($start,$end,$role,$sec,$group);
6129: foreach my $envkey (%env) {
1.1060 raeburn 6130: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6131: my $cid = $2.'_'.$3;
6132: if ($1 eq 'gr') {
6133: $group = $4;
6134: $allgroups{$cid}{$group} = $env{$envkey};
6135: } else {
6136: if ($4 eq '') {
6137: $sec = 'none';
6138: } else {
6139: $sec = $4;
6140: }
6141: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6142: }
1.811 albertel 6143: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6144: my $cid = $2.'_'.$3;
6145: if ($4 eq '') {
6146: $sec = 'none';
6147: } else {
6148: $sec = $4;
6149: }
6150: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6151: }
6152: }
6153: if (keys(%allroles) == 0) {
6154: return;
6155: }
6156: foreach my $key (@courses_and_groups) {
6157: my %content = %{$$access_hash{$key}};
6158: my $cnum = $content{'number'};
6159: my $cdom = $content{'domain'};
6160: my $cid = $cdom.'_'.$cnum;
6161: if (!exists($allroles{$cid})) {
6162: next;
6163: }
6164: foreach my $role_id (keys(%{$content{'roles'}})) {
6165: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6166: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6167: my @status = @{$content{'roles'}{$role_id}{'access'}};
6168: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6169: foreach my $role (keys(%{$allroles{$cid}})) {
6170: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6171: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6172: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6173: if (grep/^all$/,@sections) {
6174: return 'ok';
6175: } else {
6176: if (grep/^$sec$/,@sections) {
6177: return 'ok';
6178: }
6179: }
6180: }
6181: }
6182: if (keys(%{$allgroups{$cid}}) == 0) {
6183: if (grep/^none$/,@groups) {
6184: return 'ok';
6185: }
6186: } else {
6187: if (grep/^all$/,@groups) {
6188: return 'ok';
6189: }
6190: foreach my $group (keys(%{$allgroups{$cid}})) {
6191: if (grep/^$group$/,@groups) {
6192: return 'ok';
6193: }
6194: }
6195: }
6196: }
6197: }
6198: }
6199: }
6200: }
6201: if ($guest) {
6202: return $guest;
6203: }
6204: }
6205: }
6206: return;
6207: }
6208:
6209: sub course_group_datechecker {
6210: my ($dates,$now,$status) = @_;
6211: my ($start,$end) = split(/\./,$dates);
6212: if (!$start && !$end) {
6213: return 'ok';
6214: }
6215: if (grep/^active$/,@{$status}) {
6216: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6217: return 'ok';
6218: }
6219: }
6220: if (grep/^previous$/,@{$status}) {
6221: if ($end > $now ) {
6222: return 'ok';
6223: }
6224: }
6225: if (grep/^future$/,@{$status}) {
6226: if ($start > $now) {
6227: return 'ok';
6228: }
6229: }
6230: return;
6231: }
6232:
6233: sub parse_portfolio_url {
6234: my ($url) = @_;
6235:
6236: my ($type,$udom,$unum,$group,$file_name);
6237:
1.823 albertel 6238: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6239: $type = 1;
6240: $udom = $1;
6241: $unum = $2;
6242: $file_name = $3;
1.823 albertel 6243: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6244: $type = 2;
6245: $udom = $1;
6246: $unum = $2;
6247: $group = $3;
6248: $file_name = $3.'/'.$4;
6249: }
6250: if (wantarray) {
6251: return ($type,$udom,$unum,$file_name,$group);
6252: }
6253: return $type;
6254: }
6255:
6256: sub is_portfolio_url {
6257: my ($url) = @_;
6258: return scalar(&parse_portfolio_url($url));
6259: }
6260:
1.798 raeburn 6261: sub is_portfolio_file {
6262: my ($file) = @_;
1.820 raeburn 6263: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6264: return 1;
6265: }
6266: return;
6267: }
6268:
1.976 raeburn 6269: sub usertools_access {
1.1084 raeburn 6270: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6271: my ($access,%tools);
6272: if ($context eq '') {
6273: $context = 'tools';
6274: }
6275: if ($context eq 'requestcourses') {
6276: %tools = (
6277: official => 1,
6278: unofficial => 1,
1.1006 raeburn 6279: community => 1,
1.1172.2.37 raeburn 6280: textbook => 1,
1.985 raeburn 6281: );
1.1172.2.9 raeburn 6282: } elsif ($context eq 'requestauthor') {
6283: %tools = (
6284: requestauthor => 1,
6285: );
1.985 raeburn 6286: } else {
6287: %tools = (
6288: aboutme => 1,
6289: blog => 1,
1.1172.2.6 raeburn 6290: webdav => 1,
1.985 raeburn 6291: portfolio => 1,
6292: );
6293: }
1.976 raeburn 6294: return if (!defined($tools{$tool}));
6295:
1.1172.2.35 raeburn 6296: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6297: $udom = $env{'user.domain'};
6298: $uname = $env{'user.name'};
6299: }
6300:
1.978 raeburn 6301: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6302: if ($action ne 'reload') {
1.985 raeburn 6303: if ($context eq 'requestcourses') {
6304: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6305: } elsif ($context eq 'requestauthor') {
6306: return $env{'environment.canrequest.author'};
1.985 raeburn 6307: } else {
6308: return $env{'environment.availabletools.'.$tool};
6309: }
6310: }
1.976 raeburn 6311: }
6312:
1.1172.2.9 raeburn 6313: my ($toolstatus,$inststatus,$envkey);
6314: if ($context eq 'requestauthor') {
6315: $envkey = $context;
6316: } else {
6317: $envkey = $context.'.'.$tool;
6318: }
1.976 raeburn 6319:
1.985 raeburn 6320: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6321: ($action ne 'reload')) {
1.1172.2.9 raeburn 6322: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6323: $inststatus = $env{'environment.inststatus'};
6324: } else {
1.1084 raeburn 6325: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6326: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6327: $inststatus = $userenvref->{'inststatus'};
6328: } else {
1.1172.2.9 raeburn 6329: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6330: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6331: $inststatus = $userenv{'inststatus'};
6332: }
1.976 raeburn 6333: }
6334:
6335: if ($toolstatus ne '') {
6336: if ($toolstatus) {
6337: $access = 1;
6338: } else {
6339: $access = 0;
6340: }
6341: return $access;
6342: }
6343:
1.1084 raeburn 6344: my ($is_adv,%domdef);
6345: if (ref($is_advref) eq 'HASH') {
6346: $is_adv = $is_advref->{'is_adv'};
6347: } else {
6348: $is_adv = &is_advanced_user($udom,$uname);
6349: }
6350: if (ref($domdefref) eq 'HASH') {
6351: %domdef = %{$domdefref};
6352: } else {
6353: %domdef = &get_domain_defaults($udom);
6354: }
1.976 raeburn 6355: if (ref($domdef{$tool}) eq 'HASH') {
6356: if ($is_adv) {
6357: if ($domdef{$tool}{'_LC_adv'} ne '') {
6358: if ($domdef{$tool}{'_LC_adv'}) {
6359: $access = 1;
6360: } else {
6361: $access = 0;
6362: }
6363: return $access;
6364: }
6365: }
6366: if ($inststatus ne '') {
6367: my ($hasaccess,$hasnoaccess);
6368: foreach my $affiliation (split(/:/,$inststatus)) {
6369: if ($domdef{$tool}{$affiliation} ne '') {
6370: if ($domdef{$tool}{$affiliation}) {
6371: $hasaccess = 1;
6372: } else {
6373: $hasnoaccess = 1;
6374: }
6375: }
6376: }
6377: if ($hasaccess || $hasnoaccess) {
6378: if ($hasaccess) {
6379: $access = 1;
6380: } elsif ($hasnoaccess) {
6381: $access = 0;
6382: }
6383: return $access;
6384: }
6385: } else {
6386: if ($domdef{$tool}{'default'} ne '') {
6387: if ($domdef{$tool}{'default'}) {
6388: $access = 1;
6389: } elsif ($domdef{$tool}{'default'} == 0) {
6390: $access = 0;
6391: }
6392: return $access;
6393: }
6394: }
6395: } else {
1.1172.2.6 raeburn 6396: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6397: $access = 1;
6398: } else {
6399: $access = 0;
6400: }
1.976 raeburn 6401: return $access;
6402: }
6403: }
6404:
1.1050 raeburn 6405: sub is_course_owner {
6406: my ($cdom,$cnum,$udom,$uname) = @_;
6407: if (($udom eq '') || ($uname eq '')) {
6408: $udom = $env{'user.domain'};
6409: $uname = $env{'user.name'};
6410: }
6411: unless (($udom eq '') || ($uname eq '')) {
6412: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6413: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6414: return 1;
6415: } else {
6416: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6417: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6418: return 1;
6419: }
6420: }
6421: }
6422: }
6423: return;
6424: }
6425:
1.976 raeburn 6426: sub is_advanced_user {
6427: my ($udom,$uname) = @_;
1.1085 raeburn 6428: if ($udom ne '' && $uname ne '') {
6429: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6430: if (wantarray) {
6431: return ($env{'user.adv'},$env{'user.author'});
6432: } else {
6433: return $env{'user.adv'};
6434: }
1.1085 raeburn 6435: }
6436: }
1.976 raeburn 6437: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6438: my %allroles;
1.1128 raeburn 6439: my ($is_adv,$is_author);
1.976 raeburn 6440: foreach my $role (keys(%roleshash)) {
6441: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6442: my $area = '/'.$tdomain.'/'.$trest;
6443: if ($sec ne '') {
6444: $area .= '/'.$sec;
6445: }
6446: if (($area ne '') && ($trole ne '')) {
6447: my $spec=$trole.'.'.$area;
6448: if ($trole =~ /^cr\//) {
6449: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6450: } elsif ($trole ne 'gr') {
6451: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6452: }
1.1128 raeburn 6453: if ($trole eq 'au') {
6454: $is_author = 1;
6455: }
1.976 raeburn 6456: }
6457: }
6458: foreach my $role (keys(%allroles)) {
6459: last if ($is_adv);
6460: foreach my $item (split(/:/,$allroles{$role})) {
6461: if ($item ne '') {
6462: my ($privilege,$restrictions)=split(/&/,$item);
6463: if ($privilege eq 'adv') {
6464: $is_adv = 1;
6465: last;
6466: }
6467: }
6468: }
6469: }
1.1128 raeburn 6470: if (wantarray) {
6471: return ($is_adv,$is_author);
6472: }
1.976 raeburn 6473: return $is_adv;
6474: }
1.798 raeburn 6475:
1.1035 raeburn 6476: sub check_can_request {
1.1036 raeburn 6477: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6478: my $canreq = 0;
6479: my ($types,$typename) = &Apache::loncommon::course_types();
6480: my @options = ('approval','validate','autolimit');
6481: my $optregex = join('|',@options);
6482: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6483: foreach my $type (@{$types}) {
6484: if (&usertools_access($env{'user.name'},
6485: $env{'user.domain'},
6486: $type,undef,'requestcourses')) {
6487: $canreq ++;
1.1036 raeburn 6488: if (ref($request_domains) eq 'HASH') {
6489: push(@{$request_domains->{$type}},$env{'user.domain'});
6490: }
1.1035 raeburn 6491: if ($dom eq $env{'user.domain'}) {
6492: $can_request->{$type} = 1;
6493: }
6494: }
6495: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6496: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6497: if (@curr > 0) {
1.1036 raeburn 6498: foreach my $item (@curr) {
6499: if (ref($request_domains) eq 'HASH') {
6500: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6501: if ($otherdom ne '') {
6502: if (ref($request_domains->{$type}) eq 'ARRAY') {
6503: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6504: push(@{$request_domains->{$type}},$otherdom);
6505: }
6506: } else {
6507: push(@{$request_domains->{$type}},$otherdom);
6508: }
6509: }
6510: }
6511: }
6512: unless($dom eq $env{'user.domain'}) {
6513: $canreq ++;
1.1035 raeburn 6514: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6515: $can_request->{$type} = 1;
6516: }
6517: }
6518: }
6519: }
6520: }
6521: }
6522: return $canreq;
6523: }
6524:
1.341 www 6525: # ---------------------------------------------- Custom access rule evaluation
6526:
6527: sub customaccess {
6528: my ($priv,$uri)=@_;
1.807 albertel 6529: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6530: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6531: $udom = &LONCAPA::clean_domain($udom);
6532: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6533: my $access=0;
1.800 albertel 6534: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6535: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6536: if ($type eq 'user') {
6537: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6538: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6539: if ($tdom) {
6540: if ($tdom ne $env{'user.domain'}) { next; }
6541: }
1.896 albertel 6542: if ($tuname) {
6543: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6544: }
6545: $access=($effect eq 'allow');
6546: last;
6547: }
6548: } else {
6549: if ($role) {
6550: if ($role ne $urole) { next; }
6551: }
6552: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6553: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6554: if ($tdom) {
6555: if ($tdom ne $udom) { next; }
6556: }
6557: if ($tcrs) {
6558: if ($tcrs ne $ucrs) { next; }
6559: }
6560: if ($tsec) {
6561: if ($tsec ne $usec) { next; }
6562: }
6563: $access=($effect eq 'allow');
6564: last;
6565: }
6566: if ($realm eq '' && $role eq '') {
6567: $access=($effect eq 'allow');
6568: }
1.402 bowersj2 6569: }
1.341 www 6570: }
6571: return $access;
6572: }
6573:
1.103 harris41 6574: # ------------------------------------------------- Check for a user privilege
1.12 www 6575:
6576: sub allowed {
1.810 raeburn 6577: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6578: my $ver_orguri=$uri;
1.439 www 6579: $uri=&deversion($uri);
1.152 www 6580: my $orguri=$uri;
1.52 www 6581: $uri=&declutter($uri);
1.809 raeburn 6582:
1.810 raeburn 6583: if ($priv eq 'evb') {
6584: # Evade communication block restrictions for specified role in a course
6585: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6586: return $1;
6587: } else {
6588: return;
6589: }
6590: }
6591:
1.620 albertel 6592: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6593: # Free bre access to adm and meta resources
1.775 albertel 6594: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6595: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6596: && ($priv eq 'bre')) {
1.14 www 6597: return 'F';
1.159 www 6598: }
6599:
1.545 banghart 6600: # Free bre access to user's own portfolio contents
1.714 raeburn 6601: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6602: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6603: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6604: my %setters;
6605: my ($startblock,$endblock) =
6606: &Apache::loncommon::blockcheck(\%setters,'port');
6607: if ($startblock && $endblock) {
6608: return 'B';
6609: } else {
6610: return 'F';
6611: }
1.545 banghart 6612: }
6613:
1.762 raeburn 6614: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6615: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6616: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6617: if (exists($env{'request.course.id'})) {
6618: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6619: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6620: if (($domain eq $cdom) && ($name eq $cnum)) {
6621: my $courseprivid=$env{'request.course.id'};
6622: $courseprivid=~s/\_/\//;
6623: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6624: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6625: return $1;
1.762 raeburn 6626: } else {
6627: if ($env{'request.course.sec'}) {
6628: $courseprivid.='/'.$env{'request.course.sec'};
6629: }
6630: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6631: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6632: return $2;
6633: }
1.714 raeburn 6634: }
6635: }
6636: }
6637: }
6638:
1.159 www 6639: # Free bre to public access
6640:
6641: if ($priv eq 'bre') {
1.238 www 6642: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6643: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6644: return 'F';
6645: }
1.238 www 6646: if ($copyright eq 'priv') {
6647: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6648: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6649: return '';
6650: }
6651: }
6652: if ($copyright eq 'domain') {
6653: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6654: unless (($env{'user.domain'} eq $1) ||
6655: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6656: return '';
6657: }
1.262 matthew 6658: }
1.620 albertel 6659: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6660: # Library role, so allow browsing of resources in this domain.
6661: return 'F';
1.238 www 6662: }
1.341 www 6663: if ($copyright eq 'custom') {
6664: unless (&customaccess($priv,$uri)) { return ''; }
6665: }
1.14 www 6666: }
1.264 matthew 6667: # Domain coordinator is trying to create a course
1.620 albertel 6668: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6669: # uri is the requested domain in this case.
6670: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6671: # a role of dc for the domain in question.
1.620 albertel 6672: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6673: }
1.29 www 6674:
1.52 www 6675: my $thisallowed='';
6676: my $statecond=0;
6677: my $courseprivid='';
6678:
1.1039 raeburn 6679: my $ownaccess;
1.1043 raeburn 6680: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6681: if (($priv eq 'bro') && ($env{'user.author'})) {
6682: if ($uri eq '') {
6683: $ownaccess = 1;
6684: } else {
6685: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6686: my $udom = $env{'user.domain'};
6687: my $uname = $env{'user.name'};
6688: if ($uri =~ m{^\Q$udom\E/?$}) {
6689: $ownaccess = 1;
1.1040 raeburn 6690: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6691: unless ($uri =~ m{\.\./}) {
6692: $ownaccess = 1;
6693: }
6694: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6695: my $now = time;
6696: if ($uri =~ m{^([^/]+)/?$}) {
6697: my $adom = $1;
6698: foreach my $key (keys(%env)) {
1.1042 raeburn 6699: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6700: my ($start,$end) = split('.',$env{$key});
6701: if (($now >= $start) && (!$end || $end < $now)) {
6702: $ownaccess = 1;
6703: last;
6704: }
6705: }
6706: }
6707: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6708: my $adom = $1;
6709: my $aname = $2;
1.1042 raeburn 6710: foreach my $role ('ca','aa') {
6711: if ($env{"user.role.$role./$adom/$aname"}) {
6712: my ($start,$end) =
6713: split('.',$env{"user.role.$role./$adom/$aname"});
6714: if (($now >= $start) && (!$end || $end < $now)) {
6715: $ownaccess = 1;
6716: last;
6717: }
1.1039 raeburn 6718: }
6719: }
6720: }
6721: }
6722: }
6723: }
6724: }
6725:
1.52 www 6726: # Course
6727:
1.620 albertel 6728: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6729: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6730: $thisallowed.=$1;
6731: }
1.52 www 6732: }
1.29 www 6733:
1.52 www 6734: # Domain
6735:
1.620 albertel 6736: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6737: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6738: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6739: $thisallowed.=$1;
6740: }
1.12 www 6741: }
1.52 www 6742:
1.1141 raeburn 6743: # User who is not author or co-author might still be able to edit
6744: # resource of an author in the domain (e.g., if Domain Coordinator).
6745: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6746: (&allowed('mdc',$env{'request.course.id'}))) {
6747: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6748: $thisallowed.=$1;
6749: }
6750: }
6751:
1.52 www 6752: # Course: uri itself is a course
1.66 www 6753: my $courseuri=$uri;
6754: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6755: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6756:
1.620 albertel 6757: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6758: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6759: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6760: $thisallowed.=$1;
6761: }
1.12 www 6762: }
1.29 www 6763:
1.665 albertel 6764: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6765: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6766: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6767: $thisallowed='';
1.671 raeburn 6768: my ($match)=&is_on_map($uri);
6769: if ($match) {
6770: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6771: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6772: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6773: if (@blockers > 0) {
6774: $thisallowed = 'B';
6775: } else {
6776: $thisallowed.=$1;
6777: }
1.671 raeburn 6778: }
6779: } else {
1.705 albertel 6780: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6781: if ($refuri) {
6782: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6783: $thisallowed='F';
1.671 raeburn 6784: } else {
6785: $refuri=&declutter($refuri);
6786: my ($match) = &is_on_map($refuri);
6787: if ($match) {
1.1162 raeburn 6788: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6789: if (@blockers > 0) {
6790: $thisallowed = 'B';
6791: } else {
6792: $thisallowed='F';
6793: }
1.671 raeburn 6794: }
1.669 raeburn 6795: }
1.671 raeburn 6796: }
6797: }
1.314 www 6798: }
1.492 albertel 6799:
1.766 albertel 6800: if ($priv eq 'bre'
6801: && $thisallowed ne 'F'
6802: && $thisallowed ne '2'
6803: && &is_portfolio_url($uri)) {
6804: $thisallowed = &portfolio_access($uri);
6805: }
6806:
1.52 www 6807: # Full access at system, domain or course-wide level? Exit.
1.29 www 6808: if ($thisallowed=~/F/) {
6809: return 'F';
6810: }
6811:
1.52 www 6812: # If this is generating or modifying users, exit with special codes
1.29 www 6813:
1.643 www 6814: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6815: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6816: my ($audom,$auname)=split('/',$uri);
1.643 www 6817: # no author name given, so this just checks on the general right to make a co-author in this domain
6818: unless ($auname) { return $thisallowed; }
6819: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6820: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6821: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6822: ($audom ne $env{'request.role.domain'}))) { return ''; }
6823: }
1.52 www 6824: return $thisallowed;
6825: }
6826: #
1.103 harris41 6827: # Gathered so far: system, domain and course wide privileges
1.52 www 6828: #
6829: # Course: See if uri or referer is an individual resource that is part of
6830: # the course
6831:
1.620 albertel 6832: if ($env{'request.course.id'}) {
1.232 www 6833:
1.620 albertel 6834: $courseprivid=$env{'request.course.id'};
6835: if ($env{'request.course.sec'}) {
6836: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6837: }
6838: $courseprivid=~s/\_/\//;
6839: my $checkreferer=1;
1.232 www 6840: my ($match,$cond)=&is_on_map($uri);
6841: if ($match) {
6842: $statecond=$cond;
1.620 albertel 6843: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6844: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6845: my $value = $1;
6846: if ($priv eq 'bre') {
6847: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6848: if (@blockers > 0) {
6849: $thisallowed = 'B';
6850: } else {
6851: $thisallowed.=$value;
6852: }
6853: } else {
6854: $thisallowed.=$value;
6855: }
1.52 www 6856: $checkreferer=0;
6857: }
1.29 www 6858: }
1.83 www 6859:
1.148 www 6860: if ($checkreferer) {
1.620 albertel 6861: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6862: unless ($refuri) {
1.800 albertel 6863: foreach my $key (keys(%env)) {
6864: if ($key=~/^httpref\..*\*/) {
6865: my $pattern=$key;
1.156 www 6866: $pattern=~s/^httpref\.\/res\///;
1.148 www 6867: $pattern=~s/\*/\[\^\/\]\+/g;
6868: $pattern=~s/\//\\\//g;
1.152 www 6869: if ($orguri=~/$pattern/) {
1.800 albertel 6870: $refuri=$env{$key};
1.148 www 6871: }
6872: }
1.191 harris41 6873: }
1.148 www 6874: }
1.232 www 6875:
1.148 www 6876: if ($refuri) {
1.152 www 6877: $refuri=&declutter($refuri);
1.232 www 6878: my ($match,$cond)=&is_on_map($refuri);
6879: if ($match) {
6880: my $refstatecond=$cond;
1.620 albertel 6881: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6882: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6883: my $value = $1;
6884: if ($priv eq 'bre') {
6885: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6886: if (@blockers > 0) {
6887: $thisallowed = 'B';
6888: } else {
6889: $thisallowed.=$value;
6890: }
6891: } else {
6892: $thisallowed.=$value;
6893: }
1.53 www 6894: $uri=$refuri;
6895: $statecond=$refstatecond;
1.52 www 6896: }
6897: }
1.148 www 6898: }
1.29 www 6899: }
1.52 www 6900: }
1.29 www 6901:
1.52 www 6902: #
1.103 harris41 6903: # Gathered now: all privileges that could apply, and condition number
1.52 www 6904: #
6905: #
6906: # Full or no access?
6907: #
1.29 www 6908:
1.52 www 6909: if ($thisallowed=~/F/) {
6910: return 'F';
6911: }
1.29 www 6912:
1.52 www 6913: unless ($thisallowed) {
6914: return '';
6915: }
1.29 www 6916:
1.52 www 6917: # Restrictions exist, deal with them
6918: #
6919: # C:according to course preferences
6920: # R:according to resource settings
6921: # L:unless locked
6922: # X:according to user session state
6923: #
6924:
6925: # Possibly locked functionality, check all courses
1.54 www 6926: # Locks might take effect only after 10 minutes cache expiration for other
6927: # courses, and 2 minutes for current course
1.52 www 6928:
6929: my $envkey;
6930: if ($thisallowed=~/L/) {
1.1000 raeburn 6931: foreach $envkey (keys(%env)) {
1.54 www 6932: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6933: my $courseid=$2;
6934: my $roleid=$1.'.'.$2;
1.92 www 6935: $courseid=~s/^\///;
1.54 www 6936: my $expiretime=600;
1.620 albertel 6937: if ($env{'request.role'} eq $roleid) {
1.54 www 6938: $expiretime=120;
6939: }
6940: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6941: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6942: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6943: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6944: }
1.620 albertel 6945: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6946: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6947: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6948: &log($env{'user.domain'},$env{'user.name'},
6949: $env{'user.home'},
1.57 www 6950: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6951: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6952: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6953: return '';
6954: }
6955: }
1.620 albertel 6956: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6957: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6958: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6959: &log($env{'user.domain'},$env{'user.name'},
6960: $env{'user.home'},
1.57 www 6961: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6962: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6963: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6964: return '';
6965: }
6966: }
6967: }
1.29 www 6968: }
1.52 www 6969: }
6970:
6971: #
6972: # Rest of the restrictions depend on selected course
6973: #
6974:
1.620 albertel 6975: unless ($env{'request.course.id'}) {
1.766 albertel 6976: if ($thisallowed eq 'A') {
6977: return 'A';
1.814 raeburn 6978: } elsif ($thisallowed eq 'B') {
6979: return 'B';
1.766 albertel 6980: } else {
6981: return '1';
6982: }
1.52 www 6983: }
1.29 www 6984:
1.52 www 6985: #
6986: # Now user is definitely in a course
6987: #
1.53 www 6988:
6989:
6990: # Course preferences
6991:
6992: if ($thisallowed=~/C/) {
1.620 albertel 6993: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6994: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6995: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6996: =~/\Q$rolecode\E/) {
1.1103 raeburn 6997: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6998: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6999: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7000: $env{'request.course.id'});
7001: }
1.237 www 7002: return '';
7003: }
7004:
1.620 albertel 7005: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7006: =~/\Q$unamedom\E/) {
1.1103 raeburn 7007: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7008: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7009: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7010: $env{'request.course.id'});
7011: }
1.54 www 7012: return '';
7013: }
1.53 www 7014: }
7015:
7016: # Resource preferences
7017:
7018: if ($thisallowed=~/R/) {
1.620 albertel 7019: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7020: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7021: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7022: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7023: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7024: }
7025: return '';
1.54 www 7026: }
1.53 www 7027: }
1.30 www 7028:
1.246 www 7029: # Restricted by state or randomout?
1.30 www 7030:
1.52 www 7031: if ($thisallowed=~/X/) {
1.620 albertel 7032: if ($env{'acc.randomout'}) {
1.579 albertel 7033: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7034: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7035: return '';
7036: }
1.247 www 7037: }
7038: if (&condval($statecond)) {
1.52 www 7039: return '2';
7040: } else {
7041: return '';
7042: }
7043: }
1.30 www 7044:
1.766 albertel 7045: if ($thisallowed eq 'A') {
7046: return 'A';
1.814 raeburn 7047: } elsif ($thisallowed eq 'B') {
7048: return 'B';
1.766 albertel 7049: }
1.52 www 7050: return 'F';
1.232 www 7051: }
1.1162 raeburn 7052:
1.1172.2.13 raeburn 7053: # ------------------------------------------- Check construction space access
7054:
7055: sub constructaccess {
7056: my ($url,$setpriv)=@_;
7057:
7058: # We do not allow editing of previous versions of files
7059: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7060:
7061: # Get username and domain from URL
7062: my ($ownername,$ownerdomain,$ownerhome);
7063:
7064: ($ownerdomain,$ownername) =
7065: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7066:
7067: # The URL does not really point to any authorspace, forget it
7068: unless (($ownername) && ($ownerdomain)) { return ''; }
7069:
7070: # Now we need to see if the user has access to the authorspace of
7071: # $ownername at $ownerdomain
7072:
7073: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7074: # Real author for this?
7075: $ownerhome = $env{'user.home'};
7076: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7077: return ($ownername,$ownerdomain,$ownerhome);
7078: }
7079: } else {
7080: # Co-author for this?
7081: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7082: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7083: $ownerhome = &homeserver($ownername,$ownerdomain);
7084: return ($ownername,$ownerdomain,$ownerhome);
7085: }
7086: }
7087:
7088: # We don't have any access right now. If we are not possibly going to do anything about this,
7089: # we might as well leave
7090: unless ($setpriv) { return ''; }
7091:
7092: # Backdoor access?
7093: my $allowed=&allowed('eco',$ownerdomain);
7094: # Nope
7095: unless ($allowed) { return ''; }
7096: # Looks like we may have access, but could be locked by the owner of the construction space
7097: if ($allowed eq 'U') {
7098: my %blocked=&get('environment',['domcoord.author'],
7099: $ownerdomain,$ownername);
7100: # Is blocked by owner
7101: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7102: }
7103: if (($allowed eq 'F') || ($allowed eq 'U')) {
7104: # Grant temporary access
7105: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7106: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7107: if (!$update) { $update = $then; }
7108: my $refresh=$env{'user.refresh.time'};
7109: if (!$refresh) { $refresh = $update; }
7110: my $now = time;
7111: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7112: $now,'ca','constructaccess');
7113: $ownerhome = &homeserver($ownername,$ownerdomain);
7114: return($ownername,$ownerdomain,$ownerhome);
7115: }
7116: # No business here
7117: return '';
7118: }
7119:
1.1162 raeburn 7120: sub get_comm_blocks {
7121: my ($cdom,$cnum) = @_;
7122: if ($cdom eq '' || $cnum eq '') {
7123: return unless ($env{'request.course.id'});
7124: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7125: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7126: }
7127: my %commblocks;
7128: my $hashid=$cdom.'_'.$cnum;
7129: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7130: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7131: %commblocks = %{$blocksref};
7132: } else {
7133: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7134: my $cachetime = 600;
7135: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7136: }
7137: return %commblocks;
7138: }
7139:
7140: sub has_comm_blocking {
7141: my ($priv,$symb,$uri,$blocks) = @_;
7142: return unless ($env{'request.course.id'});
7143: return unless ($priv eq 'bre');
7144: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7145: my %commblocks;
7146: if (ref($blocks) eq 'HASH') {
7147: %commblocks = %{$blocks};
7148: } else {
7149: %commblocks = &get_comm_blocks();
7150: }
7151: return unless (keys(%commblocks) > 0);
7152: if (!$symb) { $symb=&symbread($uri,1); }
7153: my ($map,$resid,undef)=&decode_symb($symb);
7154: my %tocheck = (
7155: maps => $map,
7156: resources => $symb,
7157: );
7158: my @blockers;
7159: my $now = time;
1.1163 raeburn 7160: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7161: foreach my $block (keys(%commblocks)) {
7162: if ($block =~ /^(\d+)____(\d+)$/) {
7163: my ($start,$end) = ($1,$2);
7164: if ($start <= $now && $end >= $now) {
7165: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7166: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7167: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7168: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7169: unless (grep(/^\Q$block\E$/,@blockers)) {
7170: push(@blockers,$block);
7171: }
7172: }
7173: }
7174: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7175: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7176: unless (grep(/^\Q$block\E$/,@blockers)) {
7177: push(@blockers,$block);
7178: }
7179: }
7180: }
7181: }
7182: }
7183: }
7184: } elsif ($block =~ /^firstaccess____(.+)$/) {
7185: my $item = $1;
1.1163 raeburn 7186: my @to_test;
1.1162 raeburn 7187: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7188: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7189: my $check_interval;
7190: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7191: my @interval;
7192: my $type = 'map';
7193: if ($item eq 'course') {
7194: $type = 'course';
7195: @interval=&EXT("resource.0.interval");
7196: } else {
7197: if ($item =~ /___\d+___/) {
7198: $type = 'resource';
7199: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7200: if (ref($navmap)) {
7201: my $res = $navmap->getBySymb($item);
7202: push(@to_test,$res);
7203: }
1.1162 raeburn 7204: } else {
7205: my $mapsymb = &symbread($item,1);
7206: if ($mapsymb) {
7207: if (ref($navmap)) {
7208: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7209: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7210: foreach my $res (@to_test) {
1.1162 raeburn 7211: my $symb = $res->symb();
7212: next if ($symb eq $mapsymb);
7213: if ($symb ne '') {
7214: @interval=&EXT("resource.0.interval",$symb);
7215: last;
7216: }
7217: }
7218: }
7219: }
7220: }
7221: }
7222: if ($interval[0] =~ /\d+/) {
7223: my $first_access;
7224: if ($type eq 'resource') {
7225: $first_access=&get_first_access($interval[1],$item);
7226: } elsif ($type eq 'map') {
7227: $first_access=&get_first_access($interval[1],undef,$item);
7228: } else {
7229: $first_access=&get_first_access($interval[1]);
7230: }
7231: if ($first_access) {
7232: my $timesup = $first_access+$interval[0];
7233: if ($timesup > $now) {
1.1163 raeburn 7234: foreach my $res (@to_test) {
7235: if ($res->is_problem()) {
7236: if ($res->completable()) {
7237: unless (grep(/^\Q$block\E$/,@blockers)) {
7238: push(@blockers,$block);
7239: }
7240: last;
7241: }
7242: }
1.1162 raeburn 7243: }
7244: }
7245: }
7246: }
7247: }
7248: }
7249: }
7250: }
7251: }
7252: return @blockers;
7253: }
7254:
7255: sub check_docs_block {
7256: my ($docsblock,$tocheck) =@_;
7257: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7258: return;
7259: }
7260: if (ref($docsblock->{'maps'}) eq 'HASH') {
7261: if ($tocheck->{'maps'}) {
7262: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7263: return 1;
7264: }
7265: }
7266: }
7267: if (ref($docsblock->{'resources'}) eq 'HASH') {
7268: if ($tocheck->{'resources'}) {
7269: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7270: return 1;
7271: }
7272: }
7273: }
7274: return;
7275: }
7276:
1.1133 foxr 7277: #
7278: # Removes the versino from a URI and
7279: # splits it in to its filename and path to the filename.
7280: # Seems like File::Basename could have done this more clearly.
7281: # Parameters:
7282: # $uri - input URI
7283: # Returns:
7284: # Two element list consisting of
7285: # $pathname - the URI up to and excluding the trailing /
7286: # $filename - The part of the URI following the last /
7287: # NOTE:
7288: # Another realization of this is simply:
7289: # use File::Basename;
7290: # ...
7291: # $uri = shift;
7292: # $filename = basename($uri);
7293: # $path = dirname($uri);
7294: # return ($filename, $path);
7295: #
7296: # The implementation below is probably faster however.
7297: #
1.710 albertel 7298: sub split_uri_for_cond {
7299: my $uri=&deversion(&declutter(shift));
7300: my @uriparts=split(/\//,$uri);
7301: my $filename=pop(@uriparts);
7302: my $pathname=join('/',@uriparts);
7303: return ($pathname,$filename);
7304: }
1.232 www 7305: # --------------------------------------------------- Is a resource on the map?
7306:
7307: sub is_on_map {
1.710 albertel 7308: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7309: #Trying to find the conditional for the file
1.620 albertel 7310: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7311: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7312: if ($match) {
1.289 bowersj2 7313: return (1,$1);
7314: } else {
1.434 www 7315: return (0,0);
1.289 bowersj2 7316: }
1.12 www 7317: }
7318:
1.427 www 7319: # --------------------------------------------------------- Get symb from alias
7320:
7321: sub get_symb_from_alias {
7322: my $symb=shift;
7323: my ($map,$resid,$url)=&decode_symb($symb);
7324: # Already is a symb
7325: if ($url) { return $symb; }
7326: # Must be an alias
7327: my $aliassymb='';
7328: my %bighash;
1.620 albertel 7329: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7330: &GDBM_READER(),0640)) {
7331: my $rid=$bighash{'mapalias_'.$symb};
7332: if ($rid) {
7333: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7334: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7335: $resid,$bighash{'src_'.$rid});
1.427 www 7336: }
7337: untie %bighash;
7338: }
7339: return $aliassymb;
7340: }
7341:
1.12 www 7342: # ----------------------------------------------------------------- Define Role
7343:
7344: sub definerole {
7345: if (allowed('mcr','/')) {
7346: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7347: foreach my $role (split(':',$sysrole)) {
7348: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7349: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7350: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7351: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7352: return "refused:s:$crole&$cqual";
7353: }
7354: }
1.191 harris41 7355: }
1.800 albertel 7356: foreach my $role (split(':',$domrole)) {
7357: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7358: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7359: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7360: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7361: return "refused:d:$crole&$cqual";
7362: }
7363: }
1.191 harris41 7364: }
1.800 albertel 7365: foreach my $role (split(':',$courole)) {
7366: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7367: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7368: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7369: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7370: return "refused:c:$crole&$cqual";
7371: }
7372: }
1.191 harris41 7373: }
1.620 albertel 7374: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7375: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7376: "rolesdef_$rolename=".
7377: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7378: return reply($command,$env{'user.home'});
1.12 www 7379: } else {
7380: return 'refused';
7381: }
1.105 harris41 7382: }
7383:
7384: # ---------------- Make a metadata query against the network of library servers
7385:
7386: sub metadata_query {
1.1172.2.33 raeburn 7387: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7388: my %rhash;
1.845 albertel 7389: my %libserv = &all_library();
1.244 matthew 7390: my @server_list = (defined($server_array) ? @$server_array
7391: : keys(%libserv) );
7392: for my $server (@server_list) {
1.1172.2.33 raeburn 7393: my $domains = '';
7394: if (ref($domains_hash) eq 'HASH') {
7395: $domains = $domains_hash->{$server};
7396: }
1.118 harris41 7397: unless ($custom or $customshow) {
1.1172.2.33 raeburn 7398: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7399: $rhash{$server}=$reply;
7400: }
7401: else {
7402: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 7403: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7404: $server);
7405: $rhash{$server}=$reply;
7406: }
1.112 harris41 7407: }
1.118 harris41 7408: return \%rhash;
1.240 www 7409: }
7410:
7411: # ----------------------------------------- Send log queries and wait for reply
7412:
7413: sub log_query {
7414: my ($uname,$udom,$query,%filters)=@_;
7415: my $uhome=&homeserver($uname,$udom);
7416: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7417: my $uhost=&hostname($uhome);
1.800 albertel 7418: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7419: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7420: $uhome);
1.479 albertel 7421: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7422: return get_query_reply($queryid);
7423: }
7424:
1.818 raeburn 7425: # -------------------------- Update MySQL table for portfolio file
7426:
7427: sub update_portfolio_table {
1.821 raeburn 7428: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7429: if ($group ne '') {
7430: $file_name =~s /^\Q$group\E//;
7431: }
1.818 raeburn 7432: my $homeserver = &homeserver($uname,$udom);
7433: my $queryid=
1.821 raeburn 7434: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7435: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7436: my $reply = &get_query_reply($queryid);
7437: return $reply;
7438: }
7439:
1.899 raeburn 7440: # -------------------------- Update MySQL allusers table
7441:
7442: sub update_allusers_table {
7443: my ($uname,$udom,$names) = @_;
7444: my $homeserver = &homeserver($uname,$udom);
7445: my $queryid=
7446: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7447: 'lastname='.&escape($names->{'lastname'}).'%%'.
7448: 'firstname='.&escape($names->{'firstname'}).'%%'.
7449: 'middlename='.&escape($names->{'middlename'}).'%%'.
7450: 'generation='.&escape($names->{'generation'}).'%%'.
7451: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7452: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7453: return;
1.899 raeburn 7454: }
7455:
1.508 raeburn 7456: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7457:
7458: sub fetch_enrollment_query {
1.511 raeburn 7459: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7460: my $homeserver;
1.547 raeburn 7461: my $maxtries = 1;
1.508 raeburn 7462: if ($context eq 'automated') {
7463: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7464: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7465: } else {
7466: $homeserver = &homeserver($cnum,$dom);
7467: }
1.838 albertel 7468: my $host=&hostname($homeserver);
1.506 raeburn 7469: my $cmd = '';
1.1000 raeburn 7470: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7471: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7472: }
7473: $cmd =~ s/%%$//;
7474: $cmd = &escape($cmd);
7475: my $query = 'fetchenrollment';
1.620 albertel 7476: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7477: unless ($queryid=~/^\Q$host\E\_/) {
7478: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7479: return 'error: '.$queryid;
7480: }
1.506 raeburn 7481: my $reply = &get_query_reply($queryid);
1.547 raeburn 7482: my $tries = 1;
7483: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7484: $reply = &get_query_reply($queryid);
7485: $tries ++;
7486: }
1.526 raeburn 7487: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7488: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7489: } else {
1.901 albertel 7490: my @responses = split(/:/,$reply);
1.515 raeburn 7491: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7492: foreach my $line (@responses) {
7493: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7494: $$replyref{$key} = $value;
7495: }
7496: } else {
1.1117 foxr 7497: my $pathname = LONCAPA::tempdir();
1.800 albertel 7498: foreach my $line (@responses) {
7499: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7500: $$replyref{$key} = $value;
7501: if ($value > 0) {
1.800 albertel 7502: foreach my $item (@{$$affiliatesref{$key}}) {
7503: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7504: my $destname = $pathname.'/'.$filename;
7505: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7506: if ($xml_classlist =~ /^error/) {
7507: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7508: } else {
1.506 raeburn 7509: if ( open(FILE,">$destname") ) {
7510: print FILE &unescape($xml_classlist);
7511: close(FILE);
1.526 raeburn 7512: } else {
7513: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7514: }
7515: }
7516: }
7517: }
7518: }
7519: }
7520: return 'ok';
7521: }
7522: return 'error';
7523: }
7524:
1.242 www 7525: sub get_query_reply {
7526: my $queryid=shift;
1.1117 foxr 7527: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7528: my $reply='';
7529: for (1..100) {
7530: sleep 2;
7531: if (-e $replyfile.'.end') {
1.448 albertel 7532: if (open(my $fh,$replyfile)) {
1.904 albertel 7533: $reply = join('',<$fh>);
7534: close($fh);
1.240 www 7535: } else { return 'error: reply_file_error'; }
1.242 www 7536: return &unescape($reply);
7537: }
1.240 www 7538: }
1.242 www 7539: return 'timeout:'.$queryid;
1.240 www 7540: }
7541:
7542: sub courselog_query {
1.241 www 7543: #
7544: # possible filters:
7545: # url: url or symb
7546: # username
7547: # domain
7548: # action: view, submit, grade
7549: # start: timestamp
7550: # end: timestamp
7551: #
1.240 www 7552: my (%filters)=@_;
1.620 albertel 7553: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7554: if ($filters{'url'}) {
7555: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7556: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7557: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7558: }
1.620 albertel 7559: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7560: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7561: return &log_query($cname,$cdom,'courselog',%filters);
7562: }
7563:
7564: sub userlog_query {
1.858 raeburn 7565: #
7566: # possible filters:
7567: # action: log check role
7568: # start: timestamp
7569: # end: timestamp
7570: #
1.240 www 7571: my ($uname,$udom,%filters)=@_;
7572: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7573: }
7574:
1.506 raeburn 7575: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7576:
7577: sub auto_run {
1.508 raeburn 7578: my ($cnum,$cdom) = @_;
1.876 raeburn 7579: my $response = 0;
7580: my $settings;
7581: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7582: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7583: $settings = $domconfig{'autoenroll'};
7584: if ($settings->{'run'} eq '1') {
7585: $response = 1;
7586: }
7587: } else {
1.934 raeburn 7588: my $homeserver;
7589: if (&is_course($cdom,$cnum)) {
7590: $homeserver = &homeserver($cnum,$cdom);
7591: } else {
7592: $homeserver = &domain($cdom,'primary');
7593: }
7594: if ($homeserver ne 'no_host') {
7595: $response = &reply('autorun:'.$cdom,$homeserver);
7596: }
1.876 raeburn 7597: }
1.506 raeburn 7598: return $response;
7599: }
1.776 albertel 7600:
1.506 raeburn 7601: sub auto_get_sections {
1.508 raeburn 7602: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7603: my $homeserver;
7604: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7605: $homeserver = &homeserver($cnum,$cdom);
7606: }
7607: if (!defined($homeserver)) {
7608: if ($cdom =~ /^$match_domain$/) {
7609: $homeserver = &domain($cdom,'primary');
7610: }
7611: }
7612: my @secs;
7613: if (defined($homeserver)) {
7614: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7615: unless ($response eq 'refused') {
7616: @secs = split(/:/,$response);
7617: }
1.506 raeburn 7618: }
7619: return @secs;
7620: }
1.776 albertel 7621:
1.506 raeburn 7622: sub auto_new_course {
1.1099 raeburn 7623: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7624: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7625: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7626: return $response;
7627: }
1.776 albertel 7628:
1.506 raeburn 7629: sub auto_validate_courseID {
1.508 raeburn 7630: my ($cnum,$cdom,$inst_course_id) = @_;
7631: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7632: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7633: return $response;
7634: }
1.776 albertel 7635:
1.1007 raeburn 7636: sub auto_validate_instcode {
1.1020 raeburn 7637: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7638: my ($homeserver,$response);
7639: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7640: $homeserver = &homeserver($cnum,$cdom);
7641: }
7642: if (!defined($homeserver)) {
7643: if ($cdom =~ /^$match_domain$/) {
7644: $homeserver = &domain($cdom,'primary');
7645: }
7646: }
1.1065 raeburn 7647: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7648: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 7649: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7650: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7651: }
7652:
1.506 raeburn 7653: sub auto_create_password {
1.873 raeburn 7654: my ($cnum,$cdom,$authparam,$udom) = @_;
7655: my ($homeserver,$response);
1.506 raeburn 7656: my $create_passwd = 0;
7657: my $authchk = '';
1.873 raeburn 7658: if ($udom =~ /^$match_domain$/) {
7659: $homeserver = &domain($udom,'primary');
7660: }
7661: if ($homeserver eq '') {
7662: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7663: $homeserver = &homeserver($cnum,$cdom);
7664: }
7665: }
7666: if ($homeserver eq '') {
7667: $authchk = 'nodomain';
1.506 raeburn 7668: } else {
1.873 raeburn 7669: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7670: if ($response eq 'refused') {
7671: $authchk = 'refused';
7672: } else {
1.901 albertel 7673: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7674: }
1.506 raeburn 7675: }
7676: return ($authparam,$create_passwd,$authchk);
7677: }
7678:
1.706 raeburn 7679: sub auto_photo_permission {
7680: my ($cnum,$cdom,$students) = @_;
7681: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7682: my ($outcome,$perm_reqd,$conditions) =
7683: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7684: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7685: return (undef,undef);
7686: }
1.706 raeburn 7687: return ($outcome,$perm_reqd,$conditions);
7688: }
7689:
7690: sub auto_checkphotos {
7691: my ($uname,$udom,$pid) = @_;
7692: my $homeserver = &homeserver($uname,$udom);
7693: my ($result,$resulttype);
7694: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7695: &escape($uname).':'.&escape($pid),
7696: $homeserver));
1.709 albertel 7697: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7698: return (undef,undef);
7699: }
1.706 raeburn 7700: if ($outcome) {
7701: ($result,$resulttype) = split(/:/,$outcome);
7702: }
7703: return ($result,$resulttype);
7704: }
7705:
7706: sub auto_photochoice {
7707: my ($cnum,$cdom) = @_;
7708: my $homeserver = &homeserver($cnum,$cdom);
7709: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7710: &escape($cdom),
7711: $homeserver)));
1.709 albertel 7712: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7713: return (undef,undef);
7714: }
1.706 raeburn 7715: return ($update,$comment);
7716: }
7717:
7718: sub auto_photoupdate {
7719: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7720: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7721: my $host=&hostname($homeserver);
1.706 raeburn 7722: my $cmd = '';
7723: my $maxtries = 1;
1.800 albertel 7724: foreach my $affiliate (keys(%{$affiliatesref})) {
7725: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7726: }
7727: $cmd =~ s/%%$//;
7728: $cmd = &escape($cmd);
7729: my $query = 'institutionalphotos';
7730: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7731: unless ($queryid=~/^\Q$host\E\_/) {
7732: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7733: return 'error: '.$queryid;
7734: }
7735: my $reply = &get_query_reply($queryid);
7736: my $tries = 1;
7737: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7738: $reply = &get_query_reply($queryid);
7739: $tries ++;
7740: }
7741: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7742: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7743: } else {
7744: my @responses = split(/:/,$reply);
7745: my $outcome = shift(@responses);
7746: foreach my $item (@responses) {
7747: my ($key,$value) = split(/=/,$item);
7748: $$photo{$key} = $value;
7749: }
7750: return $outcome;
7751: }
7752: return 'error';
7753: }
7754:
1.521 raeburn 7755: sub auto_instcode_format {
1.793 albertel 7756: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7757: $cat_order) = @_;
1.521 raeburn 7758: my $courses = '';
1.772 raeburn 7759: my @homeservers;
1.521 raeburn 7760: if ($caller eq 'global') {
1.841 albertel 7761: my %servers = &get_servers($codedom,'library');
7762: foreach my $tryserver (keys(%servers)) {
7763: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7764: push(@homeservers,$tryserver);
7765: }
1.584 raeburn 7766: }
1.1022 raeburn 7767: } elsif ($caller eq 'requests') {
7768: if ($codedom =~ /^$match_domain$/) {
7769: my $chome = &domain($codedom,'primary');
7770: unless ($chome eq 'no_host') {
7771: push(@homeservers,$chome);
7772: }
7773: }
1.521 raeburn 7774: } else {
1.772 raeburn 7775: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7776: }
1.793 albertel 7777: foreach my $code (keys(%{$instcodes})) {
7778: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7779: }
7780: chop($courses);
1.772 raeburn 7781: my $ok_response = 0;
7782: my $response;
7783: while (@homeservers > 0 && $ok_response == 0) {
7784: my $server = shift(@homeservers);
7785: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7786: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7787: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7788: split(/:/,$response);
1.772 raeburn 7789: %{$codes} = (%{$codes},&str2hash($codes_str));
7790: push(@{$codetitles},&str2array($codetitles_str));
7791: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7792: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7793: $ok_response = 1;
7794: }
7795: }
7796: if ($ok_response) {
1.521 raeburn 7797: return 'ok';
1.772 raeburn 7798: } else {
7799: return $response;
1.521 raeburn 7800: }
7801: }
7802:
1.792 raeburn 7803: sub auto_instcode_defaults {
7804: my ($domain,$returnhash,$code_order) = @_;
7805: my @homeservers;
1.841 albertel 7806:
7807: my %servers = &get_servers($domain,'library');
7808: foreach my $tryserver (keys(%servers)) {
7809: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7810: push(@homeservers,$tryserver);
7811: }
1.792 raeburn 7812: }
1.841 albertel 7813:
1.792 raeburn 7814: my $response;
1.841 albertel 7815: foreach my $server (@homeservers) {
1.792 raeburn 7816: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7817: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7818:
7819: foreach my $pair (split(/\&/,$response)) {
7820: my ($name,$value)=split(/\=/,$pair);
7821: if ($name eq 'code_order') {
7822: @{$code_order} = split(/\&/,&unescape($value));
7823: } else {
7824: $returnhash->{&unescape($name)}=&unescape($value);
7825: }
7826: }
7827: return 'ok';
1.792 raeburn 7828: }
1.841 albertel 7829:
7830: return $response;
1.1003 raeburn 7831: }
7832:
7833: sub auto_possible_instcodes {
1.1007 raeburn 7834: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7835: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7836: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7837: return;
7838: }
1.1003 raeburn 7839: my (@homeservers,$uhome);
7840: if (defined(&domain($domain,'primary'))) {
7841: $uhome=&domain($domain,'primary');
7842: push(@homeservers,&domain($domain,'primary'));
7843: } else {
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: }
7849: }
7850: }
7851: my $response;
7852: foreach my $server (@homeservers) {
7853: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7854: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7855: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7856: split(':',$response);
7857: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7858: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7859: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7860: my ($name,$value)=split('=',$item);
7861: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7862: }
7863: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7864: my ($name,$value)=split('=',$item);
7865: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7866: }
7867: return 'ok';
7868: }
7869: return $response;
7870: }
1.792 raeburn 7871:
1.1010 raeburn 7872: sub auto_courserequest_checks {
7873: my ($dom) = @_;
1.1020 raeburn 7874: my ($homeserver,%validations);
7875: if ($dom =~ /^$match_domain$/) {
7876: $homeserver = &domain($dom,'primary');
7877: }
7878: unless ($homeserver eq 'no_host') {
7879: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7880: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7881: my @items = split(/&/,$response);
7882: foreach my $item (@items) {
7883: my ($key,$value) = split('=',$item);
7884: $validations{&unescape($key)} = &thaw_unescape($value);
7885: }
7886: }
7887: }
1.1010 raeburn 7888: return %validations;
7889: }
7890:
1.1020 raeburn 7891: sub auto_courserequest_validation {
7892: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7893: my ($homeserver,$response);
7894: if ($dom =~ /^$match_domain$/) {
7895: $homeserver = &domain($dom,'primary');
7896: }
7897: unless ($homeserver eq 'no_host') {
1.1021 raeburn 7898:
1.1020 raeburn 7899: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7900: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 7901: ':'.&escape($instcode).':'.&escape($instseclist),
7902: $homeserver));
7903: }
7904: return $response;
7905: }
7906:
1.777 albertel 7907: sub auto_validate_class_sec {
1.918 raeburn 7908: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7909: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7910: my $ownerlist;
7911: if (ref($owners) eq 'ARRAY') {
7912: $ownerlist = join(',',@{$owners});
7913: } else {
7914: $ownerlist = $owners;
7915: }
1.773 raeburn 7916: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7917: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7918: return $response;
7919: }
7920:
1.1172.2.38 raeburn 7921: sub auto_crsreq_update {
7922: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
7923: $code,$inbound) = @_;
7924: my ($homeserver,%crsreqresponse);
7925: if ($cdom =~ /^$match_domain$/) {
7926: $homeserver = &domain($cdom,'primary');
7927: }
7928: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
7929: my $info;
7930: if (ref($inbound) eq 'HASH') {
7931: $info = &freeze_escape($inbound);
7932: }
7933: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
7934: ':'.&escape($action).':'.&escape($ownername).':'.
7935: &escape($ownerdomain).':'.&escape($fullname).':'.
7936: &escape($title).':'.&escape($code).':'.$info,$homeserver);
7937: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7938: my @items = split(/&/,$response);
7939: foreach my $item (@items) {
7940: my ($key,$value) = split('=',$item);
7941: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
7942: }
7943: }
7944: }
7945: return \%crsreqresponse;
7946: }
7947:
1.679 raeburn 7948: # ------------------------------------------------------- Course Group routines
7949:
7950: sub get_coursegroups {
1.809 raeburn 7951: my ($cdom,$cnum,$group,$namespace) = @_;
7952: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7953: }
7954:
1.679 raeburn 7955: sub modify_coursegroup {
7956: my ($cdom,$cnum,$groupsettings) = @_;
7957: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7958: }
7959:
1.809 raeburn 7960: sub toggle_coursegroup_status {
7961: my ($cdom,$cnum,$group,$action) = @_;
7962: my ($from_namespace,$to_namespace);
7963: if ($action eq 'delete') {
7964: $from_namespace = 'coursegroups';
7965: $to_namespace = 'deleted_groups';
7966: } else {
7967: $from_namespace = 'deleted_groups';
7968: $to_namespace = 'coursegroups';
7969: }
7970: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7971: if (my $tmp = &error(%curr_group)) {
7972: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7973: return ('read error',$tmp);
7974: } else {
7975: my %savedsettings = %curr_group;
1.809 raeburn 7976: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7977: my $deloutcome;
7978: if ($result eq 'ok') {
1.809 raeburn 7979: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7980: } else {
7981: return ('write error',$result);
7982: }
7983: if ($deloutcome eq 'ok') {
7984: return 'ok';
7985: } else {
7986: return ('delete error',$deloutcome);
7987: }
7988: }
7989: }
7990:
1.679 raeburn 7991: sub modify_group_roles {
1.957 raeburn 7992: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7993: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7994: my $role = 'gr/'.&escape($userprivs);
7995: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7996: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7997: if ($result eq 'ok') {
7998: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7999: }
1.679 raeburn 8000: return $result;
8001: }
8002:
8003: sub modify_coursegroup_membership {
8004: my ($cdom,$cnum,$membership) = @_;
8005: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8006: return $result;
8007: }
8008:
1.682 raeburn 8009: sub get_active_groups {
8010: my ($udom,$uname,$cdom,$cnum) = @_;
8011: my $now = time;
8012: my %groups = ();
8013: foreach my $key (keys(%env)) {
1.811 albertel 8014: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8015: my ($start,$end) = split(/\./,$env{$key});
8016: if (($end!=0) && ($end<$now)) { next; }
8017: if (($start!=0) && ($start>$now)) { next; }
8018: if ($1 eq $cdom && $2 eq $cnum) {
8019: $groups{$3} = $env{$key} ;
8020: }
8021: }
8022: }
8023: return %groups;
8024: }
8025:
1.683 raeburn 8026: sub get_group_membership {
8027: my ($cdom,$cnum,$group) = @_;
8028: return(&dump('groupmembership',$cdom,$cnum,$group));
8029: }
8030:
8031: sub get_users_groups {
8032: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8033: my @usersgroups;
1.683 raeburn 8034: my $cachetime=1800;
8035:
8036: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8037: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8038: if (defined($cached)) {
1.734 albertel 8039: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8040: } else {
8041: $grouplist = '';
1.816 raeburn 8042: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8043: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8044: my $access_end = $env{'course.'.$courseid.
8045: '.default_enrollment_end_date'};
8046: my $now = time;
8047: foreach my $key (keys(%roleshash)) {
8048: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8049: my $group = $1;
8050: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8051: my $start = $2;
8052: my $end = $1;
8053: if ($start == -1) { next; } # deleted from group
8054: if (($start!=0) && ($start>$now)) { next; }
8055: if (($end!=0) && ($end<$now)) {
8056: if ($access_end && $access_end < $now) {
8057: if ($access_end - $end < 86400) {
8058: push(@usersgroups,$group);
1.733 raeburn 8059: }
8060: }
1.817 raeburn 8061: next;
1.733 raeburn 8062: }
1.817 raeburn 8063: push(@usersgroups,$group);
1.683 raeburn 8064: }
8065: }
8066: }
1.817 raeburn 8067: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8068: $grouplist = join(':',@usersgroups);
8069: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8070: }
1.733 raeburn 8071: return @usersgroups;
1.683 raeburn 8072: }
8073:
8074: sub devalidate_getgroups_cache {
8075: my ($udom,$uname,$cdom,$cnum)=@_;
8076: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8077:
1.683 raeburn 8078: my $hashid="$udom:$uname:$courseid";
8079: &devalidate_cache_new('getgroups',$hashid);
8080: }
8081:
1.12 www 8082: # ------------------------------------------------------------------ Plain Text
8083:
8084: sub plaintext {
1.988 raeburn 8085: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8086: if ($short =~ m{^cr/}) {
1.758 albertel 8087: return (split('/',$short))[-1];
8088: }
1.742 raeburn 8089: if (!defined($cid)) {
8090: $cid = $env{'request.course.id'};
8091: }
8092: my %rolenames = (
1.1008 raeburn 8093: Course => 'std',
8094: Community => 'alt1',
1.742 raeburn 8095: );
1.1037 raeburn 8096: if ($cid ne '') {
8097: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8098: unless ($forcedefault) {
8099: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8100: &Apache::lonlocal::mt_escape(\$roletext);
8101: return &Apache::lonlocal::mt($roletext);
8102: }
8103: }
8104: }
8105: if ((defined($type)) && (defined($rolenames{$type})) &&
8106: (defined($rolenames{$type})) &&
8107: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8108: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8109: } elsif ($cid ne '') {
8110: my $crstype = $env{'course.'.$cid.'.type'};
8111: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8112: (defined($prp{$short}{$rolenames{$crstype}}))) {
8113: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8114: }
1.742 raeburn 8115: }
1.1037 raeburn 8116: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8117: }
8118:
8119: # ----------------------------------------------------------------- Assign Role
8120:
8121: sub assignrole {
1.957 raeburn 8122: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8123: $context)=@_;
1.21 www 8124: my $mrole;
8125: if ($role =~ /^cr\//) {
1.393 www 8126: my $cwosec=$url;
1.811 albertel 8127: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8128: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8129: my $refused = 1;
8130: if ($context eq 'requestcourses') {
8131: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8132: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8133: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8134: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8135: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8136: if ($crsenv{'internal.courseowner'} eq
8137: $env{'user.name'}.':'.$env{'user.domain'}) {
8138: $refused = '';
8139: }
8140: }
8141: }
8142: }
8143: }
8144: if ($refused) {
8145: &logthis('Refused custom assignrole: '.
8146: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8147: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8148: return 'refused';
8149: }
1.104 www 8150: }
1.21 www 8151: $mrole='cr';
1.678 raeburn 8152: } elsif ($role =~ /^gr\//) {
8153: my $cwogrp=$url;
1.811 albertel 8154: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8155: unless (&allowed('mdg',$cwogrp)) {
8156: &logthis('Refused group assignrole: '.
8157: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8158: $env{'user.name'}.' at '.$env{'user.domain'});
8159: return 'refused';
8160: }
8161: $mrole='gr';
1.21 www 8162: } else {
1.82 www 8163: my $cwosec=$url;
1.811 albertel 8164: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8165: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8166: my $refused;
8167: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8168: if (!(&allowed('c'.$role,$url))) {
8169: $refused = 1;
8170: }
8171: } else {
8172: $refused = 1;
8173: }
1.947 raeburn 8174: if ($refused) {
1.1045 raeburn 8175: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8176: if (!$selfenroll && $context eq 'course') {
8177: my %crsenv;
8178: if ($role eq 'cc' || $role eq 'co') {
8179: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8180: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8181: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8182: if ($crsenv{'internal.courseowner'} eq
8183: $env{'user.name'}.':'.$env{'user.domain'}) {
8184: $refused = '';
8185: }
8186: }
8187: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8188: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8189: if ($crsenv{'internal.courseowner'} eq
8190: $env{'user.name'}.':'.$env{'user.domain'}) {
8191: $refused = '';
8192: }
8193: }
8194: }
8195: }
8196: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8197: $refused = '';
1.1017 raeburn 8198: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8199: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8200: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8201: my $wrongcc;
8202: if ($cnum =~ /^$match_community$/) {
8203: $wrongcc = 1 if ($role eq 'cc');
8204: } else {
8205: $wrongcc = 1 if ($role eq 'co');
8206: }
8207: unless ($wrongcc) {
8208: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8209: if ($crsenv{'internal.courseowner'} eq
8210: $env{'user.name'}.':'.$env{'user.domain'}) {
8211: $refused = '';
8212: }
1.1017 raeburn 8213: }
8214: }
1.1172.2.9 raeburn 8215: } elsif ($context eq 'requestauthor') {
8216: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8217: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8218: if ($env{'environment.requestauthor'} eq 'automatic') {
8219: $refused = '';
8220: } else {
8221: my %domdefaults = &get_domain_defaults($udom);
8222: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8223: my $checkbystatus;
8224: if ($env{'user.adv'}) {
8225: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8226: if ($disposition eq 'automatic') {
8227: $refused = '';
8228: } elsif ($disposition eq '') {
8229: $checkbystatus = 1;
8230: }
8231: } else {
8232: $checkbystatus = 1;
8233: }
8234: if ($checkbystatus) {
8235: if ($env{'environment.inststatus'}) {
8236: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8237: foreach my $type (@inststatuses) {
8238: if (($type ne '') &&
8239: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8240: $refused = '';
8241: }
8242: }
8243: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8244: $refused = '';
8245: }
8246: }
8247: }
8248: }
8249: }
1.1017 raeburn 8250: }
8251: if ($refused) {
1.947 raeburn 8252: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8253: ' '.$role.' '.$end.' '.$start.' by '.
8254: $env{'user.name'}.' at '.$env{'user.domain'});
8255: return 'refused';
8256: }
1.932 raeburn 8257: }
1.1131 raeburn 8258: } elsif ($role eq 'au') {
8259: if ($url ne '/'.$udom.'/') {
8260: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8261: ' to assign author role for '.$uname.':'.$udom.
8262: ' in domain: '.$url.' refused (wrong domain).');
8263: return 'refused';
8264: }
1.104 www 8265: }
1.21 www 8266: $mrole=$role;
8267: }
1.620 albertel 8268: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8269: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8270: if ($end) { $command.='_'.$end; }
1.21 www 8271: if ($start) {
8272: if ($end) {
1.81 www 8273: $command.='_'.$start;
1.21 www 8274: } else {
1.81 www 8275: $command.='_0_'.$start;
1.21 www 8276: }
8277: }
1.739 raeburn 8278: my $origstart = $start;
8279: my $origend = $end;
1.957 raeburn 8280: my $delflag;
1.357 www 8281: # actually delete
8282: if ($deleteflag) {
1.373 www 8283: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8284: # modify command to delete the role
1.620 albertel 8285: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8286: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8287: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8288: # set start and finish to negative values for userrolelog
8289: $start=-1;
8290: $end=-1;
1.957 raeburn 8291: $delflag = 1;
1.357 www 8292: }
8293: }
8294: # send command
1.349 www 8295: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8296: # log new user role if status is ok
1.349 www 8297: if ($answer eq 'ok') {
1.663 raeburn 8298: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 8299: if (($role eq 'cc') || ($role eq 'in') ||
8300: ($role eq 'ep') || ($role eq 'ad') ||
8301: ($role eq 'ta') || ($role eq 'st') ||
8302: ($role=~/^cr/) || ($role eq 'gr') ||
8303: ($role eq 'co')) {
1.1172.2.13 raeburn 8304: # for course roles, perform group memberships changes triggered by role change.
8305: unless ($role =~ /^gr/) {
8306: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8307: $origstart,$selfenroll,$context);
8308: }
1.1172.2.9 raeburn 8309: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8310: $selfenroll,$context);
8311: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8312: ($role eq 'au') || ($role eq 'dc')) {
8313: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8314: $context);
8315: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8316: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8317: $context);
8318: }
1.1053 raeburn 8319: if ($role eq 'cc') {
8320: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8321: }
1.349 www 8322: }
8323: return $answer;
1.169 harris41 8324: }
8325:
1.1053 raeburn 8326: sub autoupdate_coowners {
8327: my ($url,$end,$start,$uname,$udom) = @_;
8328: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8329: if (($cdom ne '') && ($cnum ne '')) {
8330: my $now = time;
8331: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8332: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8333: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8334: my $instcode = $coursehash{'internal.coursecode'};
8335: if ($instcode ne '') {
1.1056 raeburn 8336: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8337: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8338: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8339: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8340: if ($result eq 'valid') {
8341: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8342: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8343: push(@newcoowners,$coowner);
8344: }
8345: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8346: push(@newcoowners,$uname.':'.$udom);
8347: }
8348: @newcoowners = sort(@newcoowners);
8349: } else {
8350: push(@newcoowners,$uname.':'.$udom);
8351: }
8352: } else {
8353: if ($coursehash{'internal.co-owners'}) {
8354: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8355: unless ($coowner eq $uname.':'.$udom) {
8356: push(@newcoowners,$coowner);
8357: }
8358: }
8359: unless (@newcoowners > 0) {
8360: $delcoowners = 1;
8361: $coowners = '';
8362: }
8363: }
8364: }
8365: if (@newcoowners || $delcoowners) {
8366: &store_coowners($cdom,$cnum,$coursehash{'home'},
8367: $delcoowners,@newcoowners);
8368: }
8369: }
8370: }
8371: }
8372: }
8373: }
8374: }
8375:
8376: sub store_coowners {
8377: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8378: my $cid = $cdom.'_'.$cnum;
8379: my ($coowners,$delresult,$putresult);
8380: if (@newcoowners) {
8381: $coowners = join(',',@newcoowners);
8382: my %coownershash = (
8383: 'internal.co-owners' => $coowners,
8384: );
8385: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8386: if ($putresult eq 'ok') {
8387: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8388: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8389: }
8390: }
8391: }
8392: if ($delcoowners) {
8393: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8394: if ($delresult eq 'ok') {
8395: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8396: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8397: }
8398: }
8399: }
8400: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8401: my %crsinfo =
8402: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8403: if (ref($crsinfo{$cid}) eq 'HASH') {
8404: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8405: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8406: }
8407: }
8408: }
8409:
1.169 harris41 8410: # -------------------------------------------------- Modify user authentication
1.197 www 8411: # Overrides without validation
8412:
1.169 harris41 8413: sub modifyuserauth {
8414: my ($udom,$uname,$umode,$upass)=@_;
8415: my $uhome=&homeserver($uname,$udom);
1.197 www 8416: unless (&allowed('mau',$udom)) { return 'refused'; }
8417: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8418: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8419: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8420: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8421: &escape($upass),$uhome);
1.620 albertel 8422: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8423: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8424: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8425: &log($udom,,$uname,$uhome,
1.620 albertel 8426: 'Authentication changed by '.$env{'user.domain'}.', '.
8427: $env{'user.name'}.', '.$umode.
1.197 www 8428: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8429: unless ($reply eq 'ok') {
1.197 www 8430: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8431: return 'error: '.$reply;
8432: }
1.170 harris41 8433: return 'ok';
1.80 www 8434: }
8435:
1.81 www 8436: # --------------------------------------------------------------- Modify a user
1.80 www 8437:
1.81 www 8438: sub modifyuser {
1.206 matthew 8439: my ($udom, $uname, $uid,
8440: $umode, $upass, $first,
8441: $middle, $last, $gene,
1.1058 raeburn 8442: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8443: $udom= &LONCAPA::clean_domain($udom);
8444: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8445: my $showcandelete = 'none';
8446: if (ref($candelete) eq 'ARRAY') {
8447: if (@{$candelete} > 0) {
8448: $showcandelete = join(', ',@{$candelete});
8449: }
8450: }
1.81 www 8451: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8452: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8453: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8454: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8455: ' desiredhome not specified').
1.620 albertel 8456: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8457: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8458: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8459: my $newuser;
8460: if ($uhome eq 'no_host') {
8461: $newuser = 1;
8462: }
1.80 www 8463: # ----------------------------------------------------------------- Create User
1.406 albertel 8464: if (($uhome eq 'no_host') &&
8465: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8466: my $unhome='';
1.844 albertel 8467: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8468: $unhome = $desiredhome;
1.620 albertel 8469: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8470: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8471: } else { # load balancing routine for determining $unhome
1.81 www 8472: my $loadm=10000000;
1.841 albertel 8473: my %servers = &get_servers($udom,'library');
8474: foreach my $tryserver (keys(%servers)) {
8475: my $answer=reply('load',$tryserver);
8476: if (($answer=~/\d+/) && ($answer<$loadm)) {
8477: $loadm=$answer;
8478: $unhome=$tryserver;
8479: }
1.80 www 8480: }
8481: }
8482: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8483: return 'error: unable to find a home server for '.$uname.
8484: ' in domain '.$udom;
1.80 www 8485: }
8486: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8487: &escape($upass),$unhome);
8488: unless ($reply eq 'ok') {
8489: return 'error: '.$reply;
8490: }
1.230 stredwic 8491: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8492: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8493: return 'error: unable verify users home machine.';
1.80 www 8494: }
1.209 matthew 8495: } # End of creation of new user
1.80 www 8496: # ---------------------------------------------------------------------- Add ID
8497: if ($uid) {
8498: $uid=~tr/A-Z/a-z/;
8499: my %uidhash=&idrget($udom,$uname);
1.196 www 8500: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8501: && (!$forceid)) {
1.80 www 8502: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8503: return 'error: user id "'.$uid.'" does not match '.
8504: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8505: }
8506: } else {
8507: &idput($udom,($uname => $uid));
8508: }
8509: }
8510: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8511: my @tmp=&get('environment',
1.899 raeburn 8512: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8513: 'permanentemail','inststatus'],
1.134 albertel 8514: $udom,$uname);
1.1075 raeburn 8515: my (%names,%oldnames);
1.313 matthew 8516: if ($tmp[0] =~ m/^error:.*/) {
8517: %names=();
8518: } else {
8519: %names = @tmp;
1.1075 raeburn 8520: %oldnames = %names;
1.313 matthew 8521: }
1.388 www 8522: #
1.1058 raeburn 8523: # If name, email and/or uid are blank (e.g., because an uploaded file
8524: # of users did not contain them), do not overwrite existing values
8525: # unless field is in $candelete array ref.
8526: #
8527:
8528: my @fields = ('firstname','middlename','lastname','generation',
8529: 'permanentemail','id');
8530: my %newvalues;
8531: if (ref($candelete) eq 'ARRAY') {
8532: foreach my $field (@fields) {
8533: if (grep(/^\Q$field\E$/,@{$candelete})) {
8534: if ($field eq 'firstname') {
8535: $names{$field} = $first;
8536: } elsif ($field eq 'middlename') {
8537: $names{$field} = $middle;
8538: } elsif ($field eq 'lastname') {
8539: $names{$field} = $last;
8540: } elsif ($field eq 'generation') {
8541: $names{$field} = $gene;
8542: } elsif ($field eq 'permanentemail') {
8543: $names{$field} = $email;
8544: } elsif ($field eq 'id') {
8545: $names{$field} = $uid;
8546: }
8547: }
8548: }
8549: }
1.388 www 8550: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8551: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8552: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8553: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8554: if ($email) {
8555: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8556: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8557: }
1.899 raeburn 8558: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8559: if (defined($inststatus)) {
8560: $names{'inststatus'} = '';
8561: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8562: if (ref($usertypes) eq 'HASH') {
8563: my @okstatuses;
8564: foreach my $item (split(/:/,$inststatus)) {
8565: if (defined($usertypes->{$item})) {
8566: push(@okstatuses,$item);
8567: }
8568: }
8569: if (@okstatuses) {
8570: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8571: }
8572: }
8573: }
1.1075 raeburn 8574: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8575: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8576: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8577: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8578: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8579: } else {
8580: $logmsg .= ' during self creation';
8581: }
1.1075 raeburn 8582: my $changed;
8583: if ($newuser) {
8584: $changed = 1;
8585: } else {
8586: foreach my $field (@fields) {
8587: if ($names{$field} ne $oldnames{$field}) {
8588: $changed = 1;
8589: last;
8590: }
8591: }
8592: }
8593: unless ($changed) {
8594: $logmsg = 'No changes in user information needed for: '.$logmsg;
8595: &logthis($logmsg);
8596: return 'ok';
8597: }
8598: my $reply = &put('environment', \%names, $udom,$uname);
8599: if ($reply ne 'ok') {
8600: return 'error: '.$reply;
8601: }
1.1087 raeburn 8602: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8603: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8604: }
1.1075 raeburn 8605: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8606: &devalidate_cache_new('namescache',$uname.':'.$udom);
8607: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8608: &logthis($logmsg);
1.134 albertel 8609: return 'ok';
1.80 www 8610: }
8611:
1.81 www 8612: # -------------------------------------------------------------- Modify student
1.80 www 8613:
1.81 www 8614: sub modifystudent {
8615: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8616: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19 raeburn 8617: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8618: if (!$cid) {
1.620 albertel 8619: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8620: return 'not_in_class';
8621: }
1.80 www 8622: }
8623: # --------------------------------------------------------------- Make the user
1.81 www 8624: my $reply=&modifyuser
1.209 matthew 8625: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8626: $desiredhome,$email,$inststatus);
1.80 www 8627: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8628: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 8629: # student's environment
1.297 matthew 8630: $uid = undef if (!$forceid);
1.455 albertel 8631: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 8632: $gene,$usec,$end,$start,$type,$locktype,
8633: $cid,$selfenroll,$context,$credits);
1.297 matthew 8634: return $reply;
8635: }
8636:
8637: sub modify_student_enrollment {
1.1172.2.23 raeburn 8638: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8639: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8640: my ($cdom,$cnum,$chome);
8641: if (!$cid) {
1.620 albertel 8642: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8643: return 'not_in_class';
8644: }
1.620 albertel 8645: $cdom=$env{'course.'.$cid.'.domain'};
8646: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8647: } else {
8648: ($cdom,$cnum)=split(/_/,$cid);
8649: }
1.620 albertel 8650: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8651: if (!$chome) {
1.457 raeburn 8652: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8653: }
1.455 albertel 8654: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8655: # Make sure the user exists
1.81 www 8656: my $uhome=&homeserver($uname,$udom);
8657: if (($uhome eq '') || ($uhome eq 'no_host')) {
8658: return 'error: no such user';
8659: }
1.297 matthew 8660: # Get student data if we were not given enough information
8661: if (!defined($first) || $first eq '' ||
8662: !defined($last) || $last eq '' ||
8663: !defined($uid) || $uid eq '' ||
8664: !defined($middle) || $middle eq '' ||
8665: !defined($gene) || $gene eq '') {
1.294 matthew 8666: # They did not supply us with enough data to enroll the student, so
8667: # we need to pick up more information.
1.297 matthew 8668: my %tmp = &get('environment',
1.294 matthew 8669: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8670: ,$udom,$uname);
8671:
1.800 albertel 8672: #foreach my $key (keys(%tmp)) {
8673: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8674: #}
1.294 matthew 8675: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8676: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8677: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8678: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8679: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8680: }
1.556 albertel 8681: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8682: my $user = "$uname:$udom";
8683: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8684: my $reply=cput('classlist',
1.1148 raeburn 8685: {$user =>
1.1172.2.19 raeburn 8686: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8687: $cdom,$cnum);
1.1148 raeburn 8688: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8689: &devalidate_getsection_cache($udom,$uname,$cid);
8690: } else {
1.81 www 8691: return 'error: '.$reply;
8692: }
1.297 matthew 8693: # Add student role to user
1.83 www 8694: my $uurl='/'.$cid;
1.81 www 8695: $uurl=~s/\_/\//g;
8696: if ($usec) {
8697: $uurl.='/'.$usec;
8698: }
1.1148 raeburn 8699: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8700: $selfenroll,$context);
8701: if ($result ne 'ok') {
8702: if ($old_entry{$user} ne '') {
8703: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8704: } else {
8705: $reply = &del('classlist',[$user],$cdom,$cnum);
8706: }
8707: }
8708: return $result;
1.21 www 8709: }
8710:
1.556 albertel 8711: sub format_name {
8712: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8713: my $name;
8714: if ($first ne 'lastname') {
8715: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8716: } else {
8717: if ($lastname=~/\S/) {
8718: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8719: $name=~s/\s+,/,/;
8720: } else {
8721: $name.= $firstname.' '.$middlename.' '.$generation;
8722: }
8723: }
8724: $name=~s/^\s+//;
8725: $name=~s/\s+$//;
8726: $name=~s/\s+/ /g;
8727: return $name;
8728: }
8729:
1.84 www 8730: # ------------------------------------------------- Write to course preferences
8731:
8732: sub writecoursepref {
8733: my ($courseid,%prefs)=@_;
8734: $courseid=~s/^\///;
8735: $courseid=~s/\_/\//g;
8736: my ($cdomain,$cnum)=split(/\//,$courseid);
8737: my $chome=homeserver($cnum,$cdomain);
8738: if (($chome eq '') || ($chome eq 'no_host')) {
8739: return 'error: no such course';
8740: }
8741: my $cstring='';
1.800 albertel 8742: foreach my $pref (keys(%prefs)) {
8743: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8744: }
1.84 www 8745: $cstring=~s/\&$//;
8746: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8747: }
8748:
8749: # ---------------------------------------------------------- Make/modify course
8750:
8751: sub createcourse {
1.741 raeburn 8752: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8753: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8754: $url=&declutter($url);
8755: my $cid='';
1.1028 raeburn 8756: if ($context eq 'requestcourses') {
8757: my $can_create = 0;
8758: my ($ownername,$ownerdom) = split(':',$course_owner);
8759: if ($udom eq $ownerdom) {
8760: if (&usertools_access($ownername,$ownerdom,$category,undef,
8761: $context)) {
8762: $can_create = 1;
8763: }
8764: } else {
8765: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8766: $category);
8767: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8768: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8769: if (@curr > 0) {
8770: my @options = qw(approval validate autolimit);
8771: my $optregex = join('|',@options);
8772: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8773: $can_create = 1;
8774: }
8775: }
8776: }
8777: }
8778: if ($can_create) {
8779: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8780: unless (&allowed('ccc',$udom)) {
8781: return 'refused';
8782: }
1.1017 raeburn 8783: }
8784: } else {
8785: return 'refused';
8786: }
1.1028 raeburn 8787: } elsif (!&allowed('ccc',$udom)) {
8788: return 'refused';
1.84 www 8789: }
1.1011 raeburn 8790: # --------------------------------------------------------------- Get Unique ID
8791: my $uname;
8792: if ($cnum =~ /^$match_courseid$/) {
8793: my $chome=&homeserver($cnum,$udom,'true');
8794: if (($chome eq '') || ($chome eq 'no_host')) {
8795: $uname = $cnum;
8796: } else {
1.1038 raeburn 8797: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8798: }
8799: } else {
1.1038 raeburn 8800: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8801: }
8802: return $uname if ($uname =~ /^error/);
8803: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8804: if (!defined($course_server)) {
8805: if (defined(&domain($udom,'primary'))) {
8806: $course_server = &domain($udom,'primary');
8807: } else {
8808: $course_server = $env{'user.home'};
8809: }
8810: }
8811: my %host_servers =
8812: &Apache::lonnet::get_servers($udom,'library');
8813: unless ($host_servers{$course_server}) {
8814: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8815: }
1.84 www 8816: # ------------------------------------------------------------- Make the course
8817: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8818: $course_server);
1.84 www 8819: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8820: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8821: if (($uhome eq '') || ($uhome eq 'no_host')) {
8822: return 'error: no such course';
8823: }
1.271 www 8824: # ----------------------------------------------------------------- Course made
1.516 raeburn 8825: # log existence
1.1029 raeburn 8826: my $now = time;
1.918 raeburn 8827: my $newcourse = {
8828: $udom.'_'.$uname => {
1.921 raeburn 8829: description => $description,
8830: inst_code => $inst_code,
8831: owner => $course_owner,
8832: type => $crstype,
1.1029 raeburn 8833: creator => $env{'user.name'}.':'.
8834: $env{'user.domain'},
8835: created => $now,
8836: context => $context,
1.918 raeburn 8837: },
8838: };
1.921 raeburn 8839: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8840: # set toplevel url
1.271 www 8841: my $topurl=$url;
8842: unless ($nonstandard) {
8843: # ------------------------------------------ For standard courses, make top url
8844: my $mapurl=&clutter($url);
1.278 www 8845: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8846: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8847: <map>
8848: <resource id="1" type="start"></resource>
8849: <resource id="2" src="$mapurl"></resource>
8850: <resource id="3" type="finish"></resource>
8851: <link index="1" from="1" to="2"></link>
8852: <link index="2" from="2" to="3"></link>
8853: </map>
8854: ENDINITMAP
8855: $topurl=&declutter(
1.638 albertel 8856: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8857: );
8858: }
8859: # ----------------------------------------------------------- Write preferences
1.84 www 8860: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8861: ('description' => $description,
8862: 'url' => $topurl,
8863: 'internal.creator' => $env{'user.name'}.':'.
8864: $env{'user.domain'},
8865: 'internal.created' => $now,
8866: 'internal.creationcontext' => $context)
8867: );
1.84 www 8868: return '/'.$udom.'/'.$uname;
8869: }
8870:
1.1011 raeburn 8871: # ------------------------------------------------------------------- Create ID
8872: sub generate_coursenum {
1.1038 raeburn 8873: my ($udom,$crstype) = @_;
1.1011 raeburn 8874: my $domdesc = &domain($udom);
8875: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8876: my $first;
8877: if ($crstype eq 'Community') {
8878: $first = '0';
8879: } else {
8880: $first = int(1+rand(9));
8881: }
8882: my $uname=$first.
1.1011 raeburn 8883: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8884: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8885: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8886: # ----------------------------------------------- Make sure that does not exist
8887: my $uhome=&homeserver($uname,$udom,'true');
8888: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8889: if ($crstype eq 'Community') {
8890: $first = '0';
8891: } else {
8892: $first = int(1+rand(9));
8893: }
8894: $uname=$first.
1.1011 raeburn 8895: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8896: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8897: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8898: $uhome=&homeserver($uname,$udom,'true');
8899: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8900: return 'error: unable to generate unique course-ID';
8901: }
8902: }
8903: return $uname;
8904: }
8905:
1.813 albertel 8906: sub is_course {
1.1167 droeschl 8907: my ($cdom, $cnum) = scalar(@_) == 1 ?
8908: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8909:
8910: return unless $cdom and $cnum;
8911:
8912: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8913: '.');
8914:
1.1172.2.23 raeburn 8915: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8916: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8917: }
8918:
1.1015 raeburn 8919: sub store_userdata {
8920: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8921: my $result;
1.1016 raeburn 8922: if ($datakey ne '') {
1.1013 raeburn 8923: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8924: if ($udom eq '' || $uname eq '') {
8925: $udom = $env{'user.domain'};
8926: $uname = $env{'user.name'};
8927: }
8928: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8929: if (($uhome eq '') || ($uhome eq 'no_host')) {
8930: $result = 'error: no_host';
8931: } else {
8932: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8933: $storehash->{'host'} = $perlvar{'lonHostID'};
8934:
8935: my $namevalue='';
8936: foreach my $key (keys(%{$storehash})) {
8937: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8938: }
8939: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 8940: unless ($namespace eq 'courserequests') {
8941: $datakey = &escape($datakey);
8942: }
1.1105 raeburn 8943: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8944: $namevalue,$uhome);
1.1013 raeburn 8945: }
8946: } else {
8947: $result = 'error: data to store was not a hash reference';
8948: }
8949: } else {
8950: $result= 'error: invalid requestkey';
8951: }
8952: return $result;
8953: }
8954:
1.21 www 8955: # ---------------------------------------------------------- Assign Custom Role
8956:
8957: sub assigncustomrole {
1.957 raeburn 8958: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8959: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8960: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8961: }
8962:
8963: # ----------------------------------------------------------------- Revoke Role
8964:
8965: sub revokerole {
1.957 raeburn 8966: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8967: my $now=time;
1.965 raeburn 8968: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8969: }
8970:
8971: # ---------------------------------------------------------- Revoke Custom Role
8972:
8973: sub revokecustomrole {
1.957 raeburn 8974: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8975: my $now=time;
1.357 www 8976: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8977: $deleteflag,$selfenroll,$context);
1.17 www 8978: }
8979:
1.533 banghart 8980: # ------------------------------------------------------------ Disk usage
1.535 albertel 8981: sub diskusage {
1.955 raeburn 8982: my ($udom,$uname,$directorypath,$getpropath)=@_;
8983: $directorypath =~ s/\/$//;
8984: my $listing=&reply('du2:'.&escape($directorypath).':'
8985: .&escape($getpropath).':'.&escape($uname).':'
8986: .&escape($udom),homeserver($uname,$udom));
8987: if ($listing eq 'unknown_cmd') {
8988: if ($getpropath) {
8989: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8990: }
8991: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8992: }
1.514 albertel 8993: return $listing;
1.512 banghart 8994: }
8995:
1.566 banghart 8996: sub is_locked {
1.1096 raeburn 8997: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8998: my @check;
8999: my $is_locked;
1.1093 raeburn 9000: push (@check,$file_name);
1.613 albertel 9001: my %locked = &get('file_permissions',\@check,
1.620 albertel 9002: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9003: my ($tmp)=keys(%locked);
9004: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9005:
1.566 banghart 9006: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9007: $is_locked = 'false';
9008: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9009: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9010: $is_locked = 'true';
1.1096 raeburn 9011: if (ref($which) eq 'ARRAY') {
9012: push(@{$which},$entry);
9013: } else {
9014: last;
9015: }
1.745 raeburn 9016: }
9017: }
1.566 banghart 9018: } else {
9019: $is_locked = 'false';
9020: }
1.1093 raeburn 9021: return $is_locked;
1.566 banghart 9022: }
9023:
1.759 albertel 9024: sub declutter_portfile {
9025: my ($file) = @_;
1.833 albertel 9026: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9027: return $file;
9028: }
9029:
1.559 banghart 9030: # ------------------------------------------------------------- Mark as Read Only
9031:
9032: sub mark_as_readonly {
9033: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9034: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9035: my ($tmp)=keys(%current_permissions);
9036: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9037: foreach my $file (@{$files}) {
1.759 albertel 9038: $file = &declutter_portfile($file);
1.561 banghart 9039: push(@{$current_permissions{$file}},$what);
1.559 banghart 9040: }
1.613 albertel 9041: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9042: return;
9043: }
9044:
1.572 banghart 9045: # ------------------------------------------------------------Save Selected Files
9046:
9047: sub save_selected_files {
9048: my ($user, $path, @files) = @_;
9049: my $filename = $user."savedfiles";
1.573 banghart 9050: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9051: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9052: foreach my $file (@files) {
1.620 albertel 9053: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9054: }
9055: foreach my $file (@other_files) {
1.574 banghart 9056: print (OUT $file."\n");
1.572 banghart 9057: }
1.574 banghart 9058: close (OUT);
1.572 banghart 9059: return 'ok';
9060: }
9061:
1.574 banghart 9062: sub clear_selected_files {
9063: my ($user) = @_;
9064: my $filename = $user."savedfiles";
1.1117 foxr 9065: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9066: print (OUT undef);
9067: close (OUT);
9068: return ("ok");
9069: }
9070:
1.572 banghart 9071: sub files_in_path {
9072: my ($user, $path) = @_;
9073: my $filename = $user."savedfiles";
9074: my %return_files;
1.1117 foxr 9075: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9076: while (my $line_in = <IN>) {
1.574 banghart 9077: chomp ($line_in);
9078: my @paths_and_file = split (m!/!, $line_in);
9079: my $file_part = pop (@paths_and_file);
9080: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9081: $path_part.='/';
9082: my $path_and_file = $path_part.$file_part;
9083: if ($path_part eq $path) {
9084: $return_files{$file_part}= 'selected';
9085: }
9086: }
1.574 banghart 9087: close (IN);
9088: return (\%return_files);
1.572 banghart 9089: }
9090:
9091: # called in portfolio select mode, to show files selected NOT in current directory
9092: sub files_not_in_path {
9093: my ($user, $path) = @_;
9094: my $filename = $user."savedfiles";
9095: my @return_files;
9096: my $path_part;
1.1117 foxr 9097: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9098: while (my $line = <IN>) {
1.572 banghart 9099: #ok, I know it's clunky, but I want it to work
1.800 albertel 9100: my @paths_and_file = split(m|/|, $line);
9101: my $file_part = pop(@paths_and_file);
9102: chomp($file_part);
9103: my $path_part = join('/', @paths_and_file);
1.572 banghart 9104: $path_part .= '/';
9105: my $path_and_file = $path_part.$file_part;
9106: if ($path_part ne $path) {
1.800 albertel 9107: push(@return_files, ($path_and_file));
1.572 banghart 9108: }
9109: }
1.800 albertel 9110: close(OUT);
1.574 banghart 9111: return (@return_files);
1.572 banghart 9112: }
9113:
1.745 raeburn 9114: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9115:
1.745 raeburn 9116: sub get_portfile_permissions {
9117: my ($domain,$user) = @_;
1.613 albertel 9118: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9119: my ($tmp)=keys(%current_permissions);
9120: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9121: return \%current_permissions;
9122: }
9123:
9124: #---------------------------------------------Get portfolio file access controls
9125:
1.749 raeburn 9126: sub get_access_controls {
1.745 raeburn 9127: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9128: my %access;
9129: my $real_file = $file;
9130: $file =~ s/\.meta$//;
1.745 raeburn 9131: if (defined($file)) {
1.749 raeburn 9132: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9133: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9134: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9135: }
9136: }
1.745 raeburn 9137: } else {
1.749 raeburn 9138: foreach my $key (keys(%{$current_permissions})) {
9139: if ($key =~ /\0accesscontrol$/) {
9140: if (defined($group)) {
9141: if ($key !~ m-^\Q$group\E/-) {
9142: next;
9143: }
9144: }
9145: my ($fullpath) = split(/\0/,$key);
9146: if (ref($$current_permissions{$key}) eq 'HASH') {
9147: foreach my $control (keys(%{$$current_permissions{$key}})) {
9148: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9149: }
9150: }
9151: }
9152: }
9153: }
9154: return %access;
9155: }
9156:
9157: sub modify_access_controls {
9158: my ($file_name,$changes,$domain,$user)=@_;
9159: my ($outcome,$deloutcome);
9160: my %store_permissions;
9161: my %new_values;
9162: my %new_control;
9163: my %translation;
9164: my @deletions = ();
9165: my $now = time;
9166: if (exists($$changes{'activate'})) {
9167: if (ref($$changes{'activate'}) eq 'HASH') {
9168: my @newitems = sort(keys(%{$$changes{'activate'}}));
9169: my $numnew = scalar(@newitems);
9170: for (my $i=0; $i<$numnew; $i++) {
9171: my $newkey = $newitems[$i];
9172: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9173: if ($newkey =~ /^\d+:/) {
9174: $newkey =~ s/^(\d+)/$newid/;
9175: $translation{$1} = $newid;
9176: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9177: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9178: $translation{$1} = $newid;
9179: }
1.749 raeburn 9180: $new_values{$file_name."\0".$newkey} =
9181: $$changes{'activate'}{$newitems[$i]};
9182: $new_control{$newkey} = $now;
9183: }
9184: }
9185: }
9186: my %todelete;
9187: my %changed_items;
9188: foreach my $action ('delete','update') {
9189: if (exists($$changes{$action})) {
9190: if (ref($$changes{$action}) eq 'HASH') {
9191: foreach my $key (keys(%{$$changes{$action}})) {
9192: my ($itemnum) = ($key =~ /^([^:]+):/);
9193: if ($action eq 'delete') {
9194: $todelete{$itemnum} = 1;
9195: } else {
9196: $changed_items{$itemnum} = $key;
9197: }
9198: }
1.745 raeburn 9199: }
9200: }
1.749 raeburn 9201: }
9202: # get lock on access controls for file.
9203: my $lockhash = {
9204: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9205: ':'.$env{'user.domain'},
9206: };
9207: my $tries = 0;
9208: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9209:
9210: while (($gotlock ne 'ok') && $tries <3) {
9211: $tries ++;
9212: sleep 1;
9213: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9214: }
9215: if ($gotlock eq 'ok') {
9216: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9217: my ($tmp)=keys(%curr_permissions);
9218: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9219: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9220: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9221: if (ref($curr_controls) eq 'HASH') {
9222: foreach my $control_item (keys(%{$curr_controls})) {
9223: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9224: if (defined($todelete{$itemnum})) {
9225: push(@deletions,$file_name."\0".$control_item);
9226: } else {
9227: if (defined($changed_items{$itemnum})) {
9228: $new_control{$changed_items{$itemnum}} = $now;
9229: push(@deletions,$file_name."\0".$control_item);
9230: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9231: } else {
9232: $new_control{$control_item} = $$curr_controls{$control_item};
9233: }
9234: }
1.745 raeburn 9235: }
9236: }
9237: }
1.970 raeburn 9238: my ($group);
9239: if (&is_course($domain,$user)) {
9240: ($group,my $file) = split(/\//,$file_name,2);
9241: }
1.749 raeburn 9242: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9243: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9244: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9245: # remove lock
9246: my @del_lock = ($file_name."\0".'locked_access_records');
9247: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9248: my $sqlresult =
1.970 raeburn 9249: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9250: $group);
1.749 raeburn 9251: } else {
9252: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9253: }
1.749 raeburn 9254: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9255: }
9256:
1.827 raeburn 9257: sub make_public_indefinitely {
9258: my ($requrl) = @_;
9259: my $now = time;
9260: my $action = 'activate';
9261: my $aclnum = 0;
9262: if (&is_portfolio_url($requrl)) {
9263: my (undef,$udom,$unum,$file_name,$group) =
9264: &parse_portfolio_url($requrl);
9265: my $current_perms = &get_portfile_permissions($udom,$unum);
9266: my %access_controls = &get_access_controls($current_perms,
9267: $group,$file_name);
9268: foreach my $key (keys(%{$access_controls{$file_name}})) {
9269: my ($num,$scope,$end,$start) =
9270: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9271: if ($scope eq 'public') {
9272: if ($start <= $now && $end == 0) {
9273: $action = 'none';
9274: } else {
9275: $action = 'update';
9276: $aclnum = $num;
9277: }
9278: last;
9279: }
9280: }
9281: if ($action eq 'none') {
9282: return 'ok';
9283: } else {
9284: my %changes;
9285: my $newend = 0;
9286: my $newstart = $now;
9287: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9288: $changes{$action}{$newkey} = {
9289: type => 'public',
9290: time => {
9291: start => $newstart,
9292: end => $newend,
9293: },
9294: };
9295: my ($outcome,$deloutcome,$new_values,$translation) =
9296: &modify_access_controls($file_name,\%changes,$udom,$unum);
9297: return $outcome;
9298: }
9299: } else {
9300: return 'invalid';
9301: }
9302: }
9303:
1.745 raeburn 9304: #------------------------------------------------------Get Marked as Read Only
9305:
9306: sub get_marked_as_readonly {
9307: my ($domain,$user,$what,$group) = @_;
9308: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9309: my @readonly_files;
1.629 banghart 9310: my $cmp1=$what;
9311: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9312: while (my ($file_name,$value) = each(%{$current_permissions})) {
9313: if (defined($group)) {
9314: if ($file_name !~ m-^\Q$group\E/-) {
9315: next;
9316: }
9317: }
1.561 banghart 9318: if (ref($value) eq "ARRAY"){
9319: foreach my $stored_what (@{$value}) {
1.629 banghart 9320: my $cmp2=$stored_what;
1.759 albertel 9321: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9322: $cmp2=join('',@{$stored_what});
1.745 raeburn 9323: }
1.629 banghart 9324: if ($cmp1 eq $cmp2) {
1.561 banghart 9325: push(@readonly_files, $file_name);
1.745 raeburn 9326: last;
1.563 banghart 9327: } elsif (!defined($what)) {
9328: push(@readonly_files, $file_name);
1.745 raeburn 9329: last;
1.561 banghart 9330: }
9331: }
1.745 raeburn 9332: }
1.561 banghart 9333: }
9334: return @readonly_files;
9335: }
1.577 banghart 9336: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9337:
1.577 banghart 9338: sub get_marked_as_readonly_hash {
1.745 raeburn 9339: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9340: my %readonly_files;
1.745 raeburn 9341: while (my ($file_name,$value) = each(%{$current_permissions})) {
9342: if (defined($group)) {
9343: if ($file_name !~ m-^\Q$group\E/-) {
9344: next;
9345: }
9346: }
1.577 banghart 9347: if (ref($value) eq "ARRAY"){
9348: foreach my $stored_what (@{$value}) {
1.745 raeburn 9349: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9350: foreach my $lock_descriptor(@{$stored_what}) {
9351: if ($lock_descriptor eq 'graded') {
9352: $readonly_files{$file_name} = 'graded';
9353: } elsif ($lock_descriptor eq 'handback') {
9354: $readonly_files{$file_name} = 'handback';
9355: } else {
9356: if (!exists($readonly_files{$file_name})) {
9357: $readonly_files{$file_name} = 'locked';
9358: }
9359: }
1.745 raeburn 9360: }
1.750 banghart 9361: }
1.577 banghart 9362: }
9363: }
9364: }
9365: return %readonly_files;
9366: }
1.559 banghart 9367: # ------------------------------------------------------------ Unmark as Read Only
9368:
9369: sub unmark_as_readonly {
1.629 banghart 9370: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9371: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9372: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9373: $file_name = &declutter_portfile($file_name);
1.634 albertel 9374: my $symb_crs = $what;
9375: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9376: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9377: my ($tmp)=keys(%current_permissions);
9378: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9379: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9380: foreach my $file (@readonly_files) {
1.759 albertel 9381: my $clean_file = &declutter_portfile($file);
9382: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9383: my $current_locks = $current_permissions{$file};
1.563 banghart 9384: my @new_locks;
9385: my @del_keys;
9386: if (ref($current_locks) eq "ARRAY"){
9387: foreach my $locker (@{$current_locks}) {
1.632 albertel 9388: my $compare=$locker;
1.749 raeburn 9389: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9390: $compare=join('',@{$locker});
1.746 raeburn 9391: if ($compare ne $symb_crs) {
9392: push(@new_locks, $locker);
9393: }
1.563 banghart 9394: }
9395: }
1.650 albertel 9396: if (scalar(@new_locks) > 0) {
1.563 banghart 9397: $current_permissions{$file} = \@new_locks;
9398: } else {
9399: push(@del_keys, $file);
1.613 albertel 9400: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9401: delete($current_permissions{$file});
1.563 banghart 9402: }
9403: }
1.561 banghart 9404: }
1.613 albertel 9405: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9406: return;
9407: }
1.512 banghart 9408:
1.17 www 9409: # ------------------------------------------------------------ Directory lister
9410:
9411: sub dirlist {
1.955 raeburn 9412: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9413: $uri=~s/^\///;
9414: $uri=~s/\/$//;
1.253 stredwic 9415: my ($udom, $uname);
1.955 raeburn 9416: if ($getuserdir) {
1.253 stredwic 9417: $udom = $userdomain;
9418: $uname = $username;
1.955 raeburn 9419: } else {
9420: (undef,$udom,$uname)=split(/\//,$uri);
9421: if(defined($userdomain)) {
9422: $udom = $userdomain;
9423: }
9424: if(defined($username)) {
9425: $uname = $username;
9426: }
1.253 stredwic 9427: }
1.955 raeburn 9428: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9429:
1.955 raeburn 9430: $dirRoot = $perlvar{'lonDocRoot'};
9431: if (defined($getpropath)) {
9432: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9433: $dirRoot =~ s/\/$//;
1.955 raeburn 9434: } elsif (defined($getuserdir)) {
9435: my $subdir=$uname.'__';
9436: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9437: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9438: ."/$udom/$subdir/$uname";
9439: } elsif (defined($alternateRoot)) {
9440: $dirRoot = $alternateRoot;
1.751 banghart 9441: }
1.253 stredwic 9442:
9443: if($udom) {
9444: if($uname) {
1.1135 raeburn 9445: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9446: if ($uhome eq 'no_host') {
9447: return ([],'no_host');
9448: }
1.955 raeburn 9449: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9450: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9451: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9452: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9453: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9454: } else {
9455: @listing_results = map { &unescape($_); } split(/:/,$listing);
9456: }
1.605 matthew 9457: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9458: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9459: @listing_results = split(/:/,$listing);
9460: } else {
9461: @listing_results = map { &unescape($_); } split(/:/,$listing);
9462: }
1.1135 raeburn 9463: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9464: ($listing eq 'rejected') || ($listing eq 'refused') ||
9465: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9466: return ([],$listing);
9467: } else {
9468: return (\@listing_results);
1.1135 raeburn 9469: }
1.955 raeburn 9470: } elsif(!$alternateRoot) {
1.1136 raeburn 9471: my (%allusers,%listerror);
1.841 albertel 9472: my %servers = &get_servers($udom,'library');
1.955 raeburn 9473: foreach my $tryserver (keys(%servers)) {
9474: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9475: &escape($udom),$tryserver);
9476: if ($listing eq 'unknown_cmd') {
9477: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9478: $udom, $tryserver);
9479: } else {
9480: @listing_results = map { &unescape($_); } split(/:/,$listing);
9481: }
1.841 albertel 9482: if ($listing eq 'unknown_cmd') {
9483: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9484: $udom, $tryserver);
9485: @listing_results = split(/:/,$listing);
9486: } else {
9487: @listing_results =
9488: map { &unescape($_); } split(/:/,$listing);
9489: }
1.1136 raeburn 9490: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9491: ($listing eq 'rejected') || ($listing eq 'refused') ||
9492: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9493: $listerror{$tryserver} = $listing;
9494: } else {
1.841 albertel 9495: foreach my $line (@listing_results) {
9496: my ($entry) = split(/&/,$line,2);
9497: $allusers{$entry} = 1;
9498: }
9499: }
1.253 stredwic 9500: }
1.1136 raeburn 9501: my @alluserslist=();
1.800 albertel 9502: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9503: push(@alluserslist,$user.'&user');
1.253 stredwic 9504: }
1.1136 raeburn 9505: return (\@alluserslist);
1.253 stredwic 9506: } else {
1.1136 raeburn 9507: return ([],'missing username');
1.253 stredwic 9508: }
1.955 raeburn 9509: } elsif(!defined($getpropath)) {
1.1136 raeburn 9510: my $path = $perlvar{'lonDocRoot'}.'/res/';
9511: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9512: return (\@all_domains);
1.955 raeburn 9513: } else {
1.1136 raeburn 9514: return ([],'missing domain');
1.275 stredwic 9515: }
9516: }
9517:
9518: # --------------------------------------------- GetFileTimestamp
9519: # This function utilizes dirlist and returns the date stamp for
9520: # when it was last modified. It will also return an error of -1
9521: # if an error occurs
9522:
9523: sub GetFileTimestamp {
1.955 raeburn 9524: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9525: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9526: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9527: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9528: undef,$getuserdir);
9529: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9530: return -1;
9531: }
9532: if (ref($fileref) eq 'ARRAY') {
9533: my @stats = split('&',$fileref->[0]);
1.375 matthew 9534: # @stats contains first the filename, then the stat output
9535: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9536: } else {
9537: return -1;
1.253 stredwic 9538: }
1.26 www 9539: }
9540:
1.712 albertel 9541: sub stat_file {
9542: my ($uri) = @_;
1.787 albertel 9543: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9544:
1.955 raeburn 9545: my ($udom,$uname,$file);
1.712 albertel 9546: if ($uri =~ m-^/(uploaded|editupload)/-) {
9547: ($udom,$uname,$file) =
1.811 albertel 9548: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9549: $file = 'userfiles/'.$file;
9550: }
9551: if ($uri =~ m-^/res/-) {
9552: ($udom,$uname) =
1.807 albertel 9553: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9554: $file = $uri;
9555: }
9556:
9557: if (!$udom || !$uname || !$file) {
9558: # unable to handle the uri
9559: return ();
9560: }
1.956 raeburn 9561: my $getpropath;
9562: if ($file =~ /^userfiles\//) {
9563: $getpropath = 1;
9564: }
1.1136 raeburn 9565: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9566: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9567: return ();
9568: } else {
9569: if (ref($listref) eq 'ARRAY') {
9570: my @stats = split('&',$listref->[0]);
9571: shift(@stats); #filename is first
9572: return @stats;
9573: }
1.712 albertel 9574: }
9575: return ();
9576: }
9577:
1.26 www 9578: # -------------------------------------------------------- Value of a Condition
9579:
1.713 albertel 9580: # gets the value of a specific preevaluated condition
9581: # stored in the string $env{user.state.<cid>}
9582: # or looks up a condition reference in the bighash and if if hasn't
9583: # already been evaluated recurses into docondval to get the value of
9584: # the condition, then memoizing it to
9585: # $env{user.state.<cid>.<condition>}
1.40 www 9586: sub directcondval {
9587: my $number=shift;
1.620 albertel 9588: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9589: &Apache::lonuserstate::evalstate();
9590: }
1.713 albertel 9591: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9592: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9593: } elsif ($number =~ /^_/) {
9594: my $sub_condition;
9595: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9596: &GDBM_READER(),0640)) {
9597: $sub_condition=$bighash{'conditions'.$number};
9598: untie(%bighash);
9599: }
9600: my $value = &docondval($sub_condition);
1.949 raeburn 9601: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9602: return $value;
9603: }
1.620 albertel 9604: if ($env{'user.state.'.$env{'request.course.id'}}) {
9605: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9606: } else {
9607: return 2;
9608: }
9609: }
9610:
1.713 albertel 9611: # get the collection of conditions for this resource
1.26 www 9612: sub condval {
9613: my $condidx=shift;
1.54 www 9614: my $allpathcond='';
1.713 albertel 9615: foreach my $cond (split(/\|/,$condidx)) {
9616: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9617: $allpathcond.=
9618: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9619: }
1.191 harris41 9620: }
1.54 www 9621: $allpathcond=~s/\|$//;
1.713 albertel 9622: return &docondval($allpathcond);
9623: }
9624:
9625: #evaluates an expression of conditions
9626: sub docondval {
9627: my ($allpathcond) = @_;
9628: my $result=0;
9629: if ($env{'request.course.id'}
9630: && defined($allpathcond)) {
9631: my $operand='|';
9632: my @stack;
9633: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9634: if ($chunk eq '(') {
9635: push @stack,($operand,$result);
9636: } elsif ($chunk eq ')') {
9637: my $before=pop @stack;
9638: if (pop @stack eq '&') {
9639: $result=$result>$before?$before:$result;
9640: } else {
9641: $result=$result>$before?$result:$before;
9642: }
9643: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9644: $operand=$chunk;
9645: } else {
9646: my $new=directcondval($chunk);
9647: if ($operand eq '&') {
9648: $result=$result>$new?$new:$result;
9649: } else {
9650: $result=$result>$new?$result:$new;
9651: }
9652: }
9653: }
1.26 www 9654: }
9655: return $result;
1.421 albertel 9656: }
9657:
9658: # ---------------------------------------------------- Devalidate courseresdata
9659:
9660: sub devalidatecourseresdata {
9661: my ($coursenum,$coursedomain)=@_;
9662: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9663: &devalidate_cache_new('courseres',$hashid);
1.28 www 9664: }
9665:
1.763 www 9666:
1.200 www 9667: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9668: #
9669: # Parameters:
9670: # $coursenum - Number of the course.
9671: # $coursedomain - Domain at which the course was created.
9672: # Returns:
9673: # A hash of the course parameters along (I think) with timestamps
9674: # and version info.
1.877 foxr 9675:
1.624 albertel 9676: sub get_courseresdata {
9677: my ($coursenum,$coursedomain)=@_;
1.200 www 9678: my $coursehom=&homeserver($coursenum,$coursedomain);
9679: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9680: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9681: my %dumpreply;
1.417 albertel 9682: unless (defined($cached)) {
1.624 albertel 9683: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9684: $result=\%dumpreply;
1.251 albertel 9685: my ($tmp) = keys(%dumpreply);
9686: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9687: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9688: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9689: return $tmp;
1.416 albertel 9690: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9691: $result=undef;
1.599 albertel 9692: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9693: }
9694: }
1.624 albertel 9695: return $result;
9696: }
9697:
1.633 albertel 9698: sub devalidateuserresdata {
9699: my ($uname,$udom)=@_;
9700: my $hashid="$udom:$uname";
9701: &devalidate_cache_new('userres',$hashid);
9702: }
9703:
1.624 albertel 9704: sub get_userresdata {
9705: my ($uname,$udom)=@_;
9706: #most student don\'t have any data set, check if there is some data
9707: if (&EXT_cache_status($udom,$uname)) { return undef; }
9708:
9709: my $hashid="$udom:$uname";
9710: my ($result,$cached)=&is_cached_new('userres',$hashid);
9711: if (!defined($cached)) {
9712: my %resourcedata=&dump('resourcedata',$udom,$uname);
9713: $result=\%resourcedata;
9714: &do_cache_new('userres',$hashid,$result,600);
9715: }
9716: my ($tmp)=keys(%$result);
9717: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9718: return $result;
9719: }
9720: #error 2 occurs when the .db doesn't exist
9721: if ($tmp!~/error: 2 /) {
1.672 albertel 9722: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9723: " Trying to get resource data for ".
9724: $uname." at ".$udom.": ".
9725: $tmp."</font>");
9726: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9727: #&EXT_cache_set($udom,$uname);
9728: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9729: undef($tmp); # not really an error so don't send it back
1.624 albertel 9730: }
9731: return $tmp;
9732: }
1.879 foxr 9733: #----------------------------------------------- resdata - return resource data
9734: # Purpose:
9735: # Return resource data for either users or for a course.
9736: # Parameters:
9737: # $name - Course/user name.
9738: # $domain - Name of the domain the user/course is registered on.
9739: # $type - Type of thing $name is (must be 'course' or 'user'
9740: # @which - Array of names of resources desired.
9741: # Returns:
9742: # The value of the first reasource in @which that is found in the
9743: # resource hash.
9744: # Exceptional Conditions:
9745: # If the $type passed in is not valid (not the string 'course' or
9746: # 'user', an undefined reference is returned.
9747: # If none of the resources are found, an undef is returned
1.624 albertel 9748: sub resdata {
9749: my ($name,$domain,$type,@which)=@_;
9750: my $result;
9751: if ($type eq 'course') {
9752: $result=&get_courseresdata($name,$domain);
9753: } elsif ($type eq 'user') {
9754: $result=&get_userresdata($name,$domain);
9755: }
9756: if (!ref($result)) { return $result; }
1.251 albertel 9757: foreach my $item (@which) {
1.927 albertel 9758: if (defined($result->{$item->[0]})) {
9759: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9760: }
1.250 albertel 9761: }
1.291 albertel 9762: return undef;
1.200 www 9763: }
9764:
1.1172.2.31 raeburn 9765: sub get_numsuppfiles {
9766: my ($cnum,$cdom,$ignorecache)=@_;
9767: my $hashid=$cnum.':'.$cdom;
9768: my ($suppcount,$cached);
9769: unless ($ignorecache) {
9770: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9771: }
9772: unless (defined($cached)) {
9773: my $chome=&homeserver($cnum,$cdom);
9774: unless ($chome eq 'no_host') {
9775: ($suppcount,my $errors) = (0,0);
9776: my $suppmap = 'supplemental.sequence';
9777: ($suppcount,$errors) =
9778: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9779: }
9780: &do_cache_new('suppcount',$hashid,$suppcount,600);
9781: }
9782: return $suppcount;
9783: }
9784:
1.379 matthew 9785: #
9786: # EXT resource caching routines
9787: #
9788:
9789: sub clear_EXT_cache_status {
1.383 albertel 9790: &delenv('cache.EXT.');
1.379 matthew 9791: }
9792:
9793: sub EXT_cache_status {
9794: my ($target_domain,$target_user) = @_;
1.383 albertel 9795: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9796: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9797: # We know already the user has no data
9798: return 1;
9799: } else {
9800: return 0;
9801: }
9802: }
9803:
9804: sub EXT_cache_set {
9805: my ($target_domain,$target_user) = @_;
1.383 albertel 9806: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9807: #&appenv({$cachename => time});
1.379 matthew 9808: }
9809:
1.28 www 9810: # --------------------------------------------------------- Value of a Variable
1.58 www 9811: sub EXT {
1.715 albertel 9812:
1.1172.2.28 raeburn 9813: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9814: unless ($varname) { return ''; }
1.218 albertel 9815: #get real user name/domain, courseid and symb
9816: my $courseid;
1.359 albertel 9817: my $publicuser;
1.427 www 9818: if ($symbparm) {
9819: $symbparm=&get_symb_from_alias($symbparm);
9820: }
1.218 albertel 9821: if (!($uname && $udom)) {
1.790 albertel 9822: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9823: if (!$symbparm) { $symbparm=$cursymb; }
9824: } else {
1.620 albertel 9825: $courseid=$env{'request.course.id'};
1.218 albertel 9826: }
1.48 www 9827: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9828: my $rest;
1.320 albertel 9829: if (defined($therest[0])) {
1.48 www 9830: $rest=join('.',@therest);
9831: } else {
9832: $rest='';
9833: }
1.320 albertel 9834:
1.57 www 9835: my $qualifierrest=$qualifier;
9836: if ($rest) { $qualifierrest.='.'.$rest; }
9837: my $spacequalifierrest=$space;
9838: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9839: if ($realm eq 'user') {
1.48 www 9840: # --------------------------------------------------------------- user.resource
9841: if ($space eq 'resource') {
1.651 albertel 9842: if ( (defined($Apache::lonhomework::parsing_a_problem)
9843: || defined($Apache::lonhomework::parsing_a_task))
9844: &&
1.744 albertel 9845: ($symbparm eq &symbread()) ) {
9846: # if we are in the middle of processing the resource the
9847: # get the value we are planning on committing
9848: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9849: return $Apache::lonhomework::results{$qualifierrest};
9850: } else {
9851: return $Apache::lonhomework::history{$qualifierrest};
9852: }
1.335 albertel 9853: } else {
1.359 albertel 9854: my %restored;
1.620 albertel 9855: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9856: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9857: } else {
9858: %restored=&restore($symbparm,$courseid,$udom,$uname);
9859: }
1.335 albertel 9860: return $restored{$qualifierrest};
9861: }
1.48 www 9862: # ----------------------------------------------------------------- user.access
9863: } elsif ($space eq 'access') {
1.218 albertel 9864: # FIXME - not supporting calls for a specific user
1.48 www 9865: return &allowed($qualifier,$rest);
9866: # ------------------------------------------ user.preferences, user.environment
9867: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9868: if (($uname eq $env{'user.name'}) &&
9869: ($udom eq $env{'user.domain'})) {
9870: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9871: } else {
1.359 albertel 9872: my %returnhash;
9873: if (!$publicuser) {
9874: %returnhash=&userenvironment($udom,$uname,
9875: $qualifierrest);
9876: }
1.218 albertel 9877: return $returnhash{$qualifierrest};
9878: }
1.48 www 9879: # ----------------------------------------------------------------- user.course
9880: } elsif ($space eq 'course') {
1.218 albertel 9881: # FIXME - not supporting calls for a specific user
1.620 albertel 9882: return $env{join('.',('request.course',$qualifier))};
1.48 www 9883: # ------------------------------------------------------------------- user.role
9884: } elsif ($space eq 'role') {
1.218 albertel 9885: # FIXME - not supporting calls for a specific user
1.620 albertel 9886: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9887: if ($qualifier eq 'value') {
9888: return $role;
9889: } elsif ($qualifier eq 'extent') {
9890: return $where;
9891: }
9892: # ----------------------------------------------------------------- user.domain
9893: } elsif ($space eq 'domain') {
1.218 albertel 9894: return $udom;
1.48 www 9895: # ------------------------------------------------------------------- user.name
9896: } elsif ($space eq 'name') {
1.218 albertel 9897: return $uname;
1.48 www 9898: # ---------------------------------------------------- Any other user namespace
1.29 www 9899: } else {
1.359 albertel 9900: my %reply;
9901: if (!$publicuser) {
9902: %reply=&get($space,[$qualifierrest],$udom,$uname);
9903: }
9904: return $reply{$qualifierrest};
1.48 www 9905: }
1.236 www 9906: } elsif ($realm eq 'query') {
9907: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9908: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9909: [$spacequalifierrest]);
1.620 albertel 9910: return $env{'form.'.$spacequalifierrest};
1.236 www 9911: } elsif ($realm eq 'request') {
1.48 www 9912: # ------------------------------------------------------------- request.browser
9913: if ($space eq 'browser') {
1.1145 bisitz 9914: return $env{'browser.'.$qualifier};
1.57 www 9915: # ------------------------------------------------------------ request.filename
9916: } else {
1.620 albertel 9917: return $env{'request.'.$spacequalifierrest};
1.29 www 9918: }
1.28 www 9919: } elsif ($realm eq 'course') {
1.48 www 9920: # ---------------------------------------------------------- course.description
1.620 albertel 9921: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9922: } elsif ($realm eq 'resource') {
1.165 www 9923:
1.620 albertel 9924: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9925: if (!$symbparm) { $symbparm=&symbread(); }
9926: }
1.693 albertel 9927:
1.1172.2.30 raeburn 9928: if ($qualifier eq '') {
9929: if ($space eq 'title') {
9930: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9931: return &gettitle($symbparm);
9932: }
1.693 albertel 9933:
1.1172.2.30 raeburn 9934: if ($space eq 'map') {
9935: my ($map) = &decode_symb($symbparm);
9936: return &symbread($map);
9937: }
9938: if ($space eq 'maptitle') {
9939: my ($map) = &decode_symb($symbparm);
9940: return &gettitle($map);
9941: }
9942: if ($space eq 'filename') {
9943: if ($symbparm) {
9944: return &clutter((&decode_symb($symbparm))[2]);
9945: }
9946: return &hreflocation('',$env{'request.filename'});
1.905 albertel 9947: }
1.1172.2.30 raeburn 9948:
9949: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
9950: if ($space eq 'visibleparts') {
9951: my $navmap = Apache::lonnavmaps::navmap->new();
9952: my $item;
9953: if (ref($navmap)) {
9954: my $res = $navmap->getBySymb($symbparm);
9955: my $parts = $res->parts();
9956: if (ref($parts) eq 'ARRAY') {
9957: $item = join(',',@{$parts});
9958: }
9959: undef($navmap);
9960: }
9961: return $item;
9962: }
9963: }
9964: }
1.693 albertel 9965:
9966: my ($section, $group, @groups);
1.593 albertel 9967: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 9968: if (($courseid eq '') && ($cid)) {
9969: $courseid = $cid;
9970: }
9971: if (($symbparm && $courseid) &&
9972: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 9973:
1.218 albertel 9974: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9975:
1.60 www 9976: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9977: my $symbp=$symbparm;
1.735 albertel 9978: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9979:
9980: my $symbparm=$symbp.'.'.$spacequalifierrest;
9981: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9982:
1.620 albertel 9983: if (($env{'user.name'} eq $uname) &&
9984: ($env{'user.domain'} eq $udom)) {
9985: $section=$env{'request.course.sec'};
1.733 raeburn 9986: @groups = split(/:/,$env{'request.course.groups'});
9987: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9988: } else {
1.539 albertel 9989: if (! defined($usection)) {
1.551 albertel 9990: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9991: } else {
9992: $section = $usection;
9993: }
1.733 raeburn 9994: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9995: }
9996:
9997: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9998: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9999: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10000:
1.593 albertel 10001: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10002: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10003: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10004:
1.60 www 10005: # ----------------------------------------------------------- first, check user
1.624 albertel 10006:
10007: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10008: ([$courselevelr,'resource'],
10009: [$courselevelm,'map' ],
10010: [$courselevel, 'course' ]));
1.931 albertel 10011: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10012:
1.594 albertel 10013: # ------------------------------------------------ second, check some of course
1.684 raeburn 10014: my $coursereply;
1.691 raeburn 10015: if (@groups > 0) {
10016: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10017: $mapparm,$spacequalifierrest);
1.927 albertel 10018: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10019: }
1.96 www 10020:
1.684 raeburn 10021: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10022: $env{'course.'.$courseid.'.domain'},
10023: 'course',
10024: ([$seclevelr, 'resource'],
10025: [$seclevelm, 'map' ],
10026: [$seclevel, 'course' ],
10027: [$courselevelr,'resource']));
10028: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10029:
1.60 www 10030: # ------------------------------------------------------ third, check map parms
1.218 albertel 10031: my %parmhash=();
10032: my $thisparm='';
10033: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10034: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10035: &GDBM_READER(),0640)) {
1.218 albertel 10036: $thisparm=$parmhash{$symbparm};
10037: untie(%parmhash);
10038: }
1.927 albertel 10039: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10040: }
1.594 albertel 10041: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10042:
1.218 albertel 10043: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10044: my $filename;
10045: if (!$symbparm) { $symbparm=&symbread(); }
10046: if ($symbparm) {
1.409 www 10047: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10048: } else {
1.620 albertel 10049: $filename=$env{'request.filename'};
1.282 albertel 10050: }
10051: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10052: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10053: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10054: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10055:
1.927 albertel 10056: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10057: if ($symbparm && defined($courseid) &&
1.620 albertel 10058: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10059: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10060: $env{'course.'.$courseid.'.domain'},
10061: 'course',
1.927 albertel 10062: ([$courselevelm,'map' ],
10063: [$courselevel, 'course']));
10064: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10065: }
1.145 www 10066: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10067: unless ($space eq '0') {
1.336 albertel 10068: my @parts=split(/_/,$space);
10069: my $id=pop(@parts);
10070: my $part=join('_',@parts);
10071: if ($part eq '') { $part='0'; }
1.927 albertel 10072: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10073: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10074: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10075: }
1.395 albertel 10076: if ($recurse) { return undef; }
10077: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10078: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10079: # ---------------------------------------------------- Any other user namespace
10080: } elsif ($realm eq 'environment') {
10081: # ----------------------------------------------------------------- environment
1.620 albertel 10082: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10083: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10084: } else {
1.770 albertel 10085: if ($uname eq 'anonymous' && $udom eq '') {
10086: return '';
10087: }
1.219 albertel 10088: my %returnhash=&userenvironment($udom,$uname,
10089: $spacequalifierrest);
10090: return $returnhash{$spacequalifierrest};
10091: }
1.28 www 10092: } elsif ($realm eq 'system') {
1.48 www 10093: # ----------------------------------------------------------------- system.time
10094: if ($space eq 'time') {
10095: return time;
10096: }
1.696 albertel 10097: } elsif ($realm eq 'server') {
10098: # ----------------------------------------------------------------- system.time
10099: if ($space eq 'name') {
10100: return $ENV{'SERVER_NAME'};
10101: }
1.28 www 10102: }
1.48 www 10103: return '';
1.61 www 10104: }
10105:
1.927 albertel 10106: sub get_reply {
10107: my ($reply_value) = @_;
1.940 raeburn 10108: if (ref($reply_value) eq 'ARRAY') {
10109: if (wantarray) {
10110: return @$reply_value;
10111: }
10112: return $reply_value->[0];
10113: } else {
10114: return $reply_value;
1.927 albertel 10115: }
10116: }
10117:
1.691 raeburn 10118: sub check_group_parms {
10119: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10120: my @groupitems = ();
10121: my $resultitem;
1.927 albertel 10122: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10123: foreach my $group (@{$groups}) {
10124: foreach my $level (@levels) {
1.927 albertel 10125: my $item = $courseid.'.['.$group.'].'.$level->[0];
10126: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10127: }
10128: }
10129: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10130: $env{'course.'.$courseid.'.domain'},
10131: 'course',@groupitems);
10132: return $coursereply;
10133: }
10134:
10135: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10136: my ($courseid,@groups) = @_;
10137: @groups = sort(@groups);
1.691 raeburn 10138: return @groups;
10139: }
10140:
1.395 albertel 10141: sub packages_tab_default {
10142: my ($uri,$varname)=@_;
10143: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10144:
10145: my (@extension,@specifics,$do_default);
10146: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10147: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10148: if ($pack_type eq 'default') {
10149: $do_default=1;
10150: } elsif ($pack_type eq 'extension') {
10151: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10152: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10153: # only look at packages defaults for packages that this id is
1.738 albertel 10154: push(@specifics,[$package,$pack_type,$pack_part]);
10155: }
10156: }
10157: # first look for a package that matches the requested part id
10158: foreach my $package (@specifics) {
10159: my (undef,$pack_type,$pack_part)=@{$package};
10160: next if ($pack_part ne $part);
10161: if (defined($packagetab{"$pack_type&$name&default"})) {
10162: return $packagetab{"$pack_type&$name&default"};
10163: }
10164: }
10165: # look for any possible matching non extension_ package
10166: foreach my $package (@specifics) {
10167: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10168: if (defined($packagetab{"$pack_type&$name&default"})) {
10169: return $packagetab{"$pack_type&$name&default"};
10170: }
1.585 albertel 10171: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10172: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10173: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10174: }
10175: }
1.738 albertel 10176: # look for any posible extension_ match
10177: foreach my $package (@extension) {
10178: my ($package,$pack_type)=@{$package};
10179: if (defined($packagetab{"$pack_type&$name&default"})) {
10180: return $packagetab{"$pack_type&$name&default"};
10181: }
10182: if (defined($packagetab{$package."&$name&default"})) {
10183: return $packagetab{$package."&$name&default"};
10184: }
10185: }
10186: # look for a global default setting
10187: if ($do_default && defined($packagetab{"default&$name&default"})) {
10188: return $packagetab{"default&$name&default"};
10189: }
1.395 albertel 10190: return undef;
10191: }
10192:
1.334 albertel 10193: sub add_prefix_and_part {
10194: my ($prefix,$part)=@_;
10195: my $keyroot;
10196: if (defined($prefix) && $prefix !~ /^__/) {
10197: # prefix that has a part already
10198: $keyroot=$prefix;
10199: } elsif (defined($prefix)) {
10200: # prefix that is missing a part
10201: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10202: } else {
10203: # no prefix at all
10204: if (defined($part)) { $keyroot='_'.$part; }
10205: }
10206: return $keyroot;
10207: }
10208:
1.71 www 10209: # ---------------------------------------------------------------- Get metadata
10210:
1.599 albertel 10211: my %metaentry;
1.1070 www 10212: my %importedpartids;
1.71 www 10213: sub metadata {
1.176 www 10214: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10215: $uri=&declutter($uri);
1.288 albertel 10216: # if it is a non metadata possible uri return quickly
1.529 albertel 10217: if (($uri eq '') ||
10218: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 10219: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10220: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10221: return undef;
10222: }
1.1140 www 10223: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 10224: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10225: return undef;
1.288 albertel 10226: }
1.73 www 10227: my $filename=$uri;
10228: $uri=~s/\.meta$//;
1.172 www 10229: #
10230: # Is the metadata already cached?
1.177 www 10231: # Look at timestamp of caching
1.172 www 10232: # Everything is cached by the main uri, libraries are never directly cached
10233: #
1.428 albertel 10234: if (!defined($liburi)) {
1.599 albertel 10235: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10236: if (defined($cached)) { return $result->{':'.$what}; }
10237: }
10238: {
1.1069 www 10239: # Imported parts would go here
1.1070 www 10240: my %importedids=();
10241: my @origfileimportpartids=();
1.1069 www 10242: my $importedparts=0;
1.172 www 10243: #
10244: # Is this a recursive call for a library?
10245: #
1.599 albertel 10246: # if (! exists($metacache{$uri})) {
10247: # $metacache{$uri}={};
10248: # }
1.924 albertel 10249: my $cachetime = 60*60;
1.171 www 10250: if ($liburi) {
10251: $liburi=&declutter($liburi);
10252: $filename=$liburi;
1.401 bowersj2 10253: } else {
1.599 albertel 10254: &devalidate_cache_new('meta',$uri);
10255: undef(%metaentry);
1.401 bowersj2 10256: }
1.140 www 10257: my %metathesekeys=();
1.73 www 10258: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10259: my $metastring;
1.1140 www 10260: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10261: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10262: $metastring =
1.929 albertel 10263: &Apache::lonnet::ssi_body($which,
1.924 albertel 10264: ('grade_target' => 'meta'));
10265: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10266: } elsif (($uri !~ m -^(editupload)/-) &&
10267: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10268: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10269: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10270: $metastring=&getfile($file);
1.489 albertel 10271: }
1.208 albertel 10272: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10273: my $token;
1.140 www 10274: undef %metathesekeys;
1.71 www 10275: while ($token=$parser->get_token) {
1.339 albertel 10276: if ($token->[0] eq 'S') {
10277: if (defined($token->[2]->{'package'})) {
1.172 www 10278: #
10279: # This is a package - get package info
10280: #
1.339 albertel 10281: my $package=$token->[2]->{'package'};
10282: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10283: if (defined($token->[2]->{'id'})) {
10284: $keyroot.='_'.$token->[2]->{'id'};
10285: }
1.599 albertel 10286: if ($metaentry{':packages'}) {
10287: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10288: } else {
1.599 albertel 10289: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10290: }
1.736 albertel 10291: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10292: my $part=$keyroot;
10293: $part=~s/^\_//;
1.736 albertel 10294: if ($pack_entry=~/^\Q$package\E\&/ ||
10295: $pack_entry=~/^\Q$package\E_0\&/) {
10296: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10297: # ignore package.tab specified default values
10298: # here &package_tab_default() will fetch those
10299: if ($subp eq 'default') { next; }
1.736 albertel 10300: my $value=$packagetab{$pack_entry};
1.432 albertel 10301: my $unikey;
10302: if ($pack =~ /_0$/) {
10303: $unikey='parameter_0_'.$name;
10304: $part=0;
10305: } else {
10306: $unikey='parameter'.$keyroot.'_'.$name;
10307: }
1.339 albertel 10308: if ($subp eq 'display') {
10309: $value.=' [Part: '.$part.']';
10310: }
1.599 albertel 10311: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10312: $metathesekeys{$unikey}=1;
1.599 albertel 10313: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10314: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10315: }
1.599 albertel 10316: if (defined($metaentry{':'.$unikey.'.default'})) {
10317: $metaentry{':'.$unikey}=
10318: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10319: }
1.339 albertel 10320: }
10321: }
10322: } else {
1.172 www 10323: #
10324: # This is not a package - some other kind of start tag
1.339 albertel 10325: #
10326: my $entry=$token->[1];
1.1068 www 10327: my $unikey='';
1.175 www 10328:
1.339 albertel 10329: if ($entry eq 'import') {
1.175 www 10330: #
10331: # Importing a library here
1.339 albertel 10332: #
1.1067 www 10333: my $location=$parser->get_text('/import');
10334: my $dir=$filename;
10335: $dir=~s|[^/]*$||;
10336: $location=&filelocation($dir,$location);
1.1069 www 10337:
1.1068 www 10338: my $importmode=$token->[2]->{'importmode'};
10339: if ($importmode eq 'problem') {
1.1069 www 10340: # Import as problem/response
1.1068 www 10341: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10342: } elsif ($importmode eq 'part') {
10343: # Import as part(s)
1.1069 www 10344: $importedparts=1;
10345: # We need to get the original file and the imported file to get the part order correct
10346: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10347: # Load and inspect original file
1.1070 www 10348: if ($#origfileimportpartids<0) {
10349: undef(%importedpartids);
10350: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10351: my $origfile=&getfile($origfilelocation);
10352: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10353: }
10354:
1.1069 www 10355: # Load and inspect imported file
10356: my $impfile=&getfile($location);
10357: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10358: if ($#impfilepartids>=0) {
10359: # This problem had parts
1.1070 www 10360: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10361: } else {
10362: # Importing by turning a single problem into a problem part
10363: # It gets the import-tags ID as part-ID
10364: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10365: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10366: }
1.1068 www 10367: } else {
10368: # Normal import
10369: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10370: if (defined($token->[2]->{'id'})) {
10371: $unikey.='_'.$token->[2]->{'id'};
10372: }
1.1067 www 10373: }
10374:
1.339 albertel 10375: if ($depthcount<20) {
1.736 albertel 10376: my $metadata =
10377: &metadata($uri,'keys', $location,$unikey,
10378: $depthcount+1);
10379: foreach my $meta (split(',',$metadata)) {
10380: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10381: $metathesekeys{$meta}=1;
1.339 albertel 10382: }
1.1068 www 10383:
10384: }
1.1067 www 10385: } else {
10386: #
10387: # Not importing, some other kind of non-package, non-library start tag
10388: #
10389: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10390: if (defined($token->[2]->{'id'})) {
10391: $unikey.='_'.$token->[2]->{'id'};
10392: }
1.339 albertel 10393: if (defined($token->[2]->{'name'})) {
10394: $unikey.='_'.$token->[2]->{'name'};
10395: }
10396: $metathesekeys{$unikey}=1;
1.736 albertel 10397: foreach my $param (@{$token->[3]}) {
10398: $metaentry{':'.$unikey.'.'.$param} =
10399: $token->[2]->{$param};
1.339 albertel 10400: }
10401: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10402: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10403: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10404: # only ws inside the tag, and not in default, so use default
10405: # as value
1.599 albertel 10406: $metaentry{':'.$unikey}=$default;
1.908 albertel 10407: } elsif ( $internaltext =~ /\S/ ) {
10408: # something interesting inside the tag
10409: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10410: } else {
1.908 albertel 10411: # no interesting values, don't set a default
1.339 albertel 10412: }
1.172 www 10413: # end of not-a-package not-a-library import
1.339 albertel 10414: }
1.172 www 10415: # end of not-a-package start tag
1.339 albertel 10416: }
1.172 www 10417: # the next is the end of "start tag"
1.339 albertel 10418: }
10419: }
1.483 albertel 10420: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10421: $extension = lc($extension);
10422: if ($extension eq 'htm') { $extension='html'; }
10423:
1.737 albertel 10424: foreach my $key (keys(%packagetab)) {
1.483 albertel 10425: #no specific packages #how's our extension
10426: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10427: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10428: \%metathesekeys);
10429: }
1.883 albertel 10430:
10431: if (!exists($metaentry{':packages'})
10432: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10433: foreach my $key (keys(%packagetab)) {
1.483 albertel 10434: #no specific packages well let's get default then
10435: if ($key!~/^default&/) { next; }
1.488 albertel 10436: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10437: \%metathesekeys);
10438: }
10439: }
1.338 www 10440: # are there custom rights to evaluate
1.599 albertel 10441: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10442:
1.338 www 10443: #
10444: # Importing a rights file here
1.339 albertel 10445: #
10446: unless ($depthcount) {
1.599 albertel 10447: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10448: my $dir=$filename;
10449: $dir=~s|[^/]*$||;
10450: $location=&filelocation($dir,$location);
1.736 albertel 10451: my $rights_metadata =
10452: &metadata($uri,'keys',$location,'_rights',
10453: $depthcount+1);
10454: foreach my $rights (split(',',$rights_metadata)) {
10455: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10456: $metathesekeys{$rights}=1;
1.339 albertel 10457: }
10458: }
10459: }
1.737 albertel 10460: # uniqifiy package listing
10461: my %seen;
10462: my @uniq_packages =
10463: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10464: $metaentry{':packages'} = join(',',@uniq_packages);
10465:
1.1070 www 10466: if ($importedparts) {
10467: # We had imported parts and need to rebuild partorder
10468: $metaentry{':partorder'}='';
10469: $metathesekeys{'partorder'}=1;
10470: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10471: if ($origfileimportpartids[$index] eq 'part') {
10472: # original part, part of the problem
10473: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10474: } else {
10475: # we have imported parts at this position
10476: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10477: }
10478: }
10479: $metaentry{':partorder'}=~s/^\,//;
10480: }
10481:
1.737 albertel 10482: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10483: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10484: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 10485: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10486: # this is the end of "was not already recently cached
1.71 www 10487: }
1.599 albertel 10488: return $metaentry{':'.$what};
1.261 albertel 10489: }
10490:
1.488 albertel 10491: sub metadata_create_package_def {
1.483 albertel 10492: my ($uri,$key,$package,$metathesekeys)=@_;
10493: my ($pack,$name,$subp)=split(/\&/,$key);
10494: if ($subp eq 'default') { next; }
10495:
1.599 albertel 10496: if (defined($metaentry{':packages'})) {
10497: $metaentry{':packages'}.=','.$package;
1.483 albertel 10498: } else {
1.599 albertel 10499: $metaentry{':packages'}=$package;
1.483 albertel 10500: }
10501: my $value=$packagetab{$key};
10502: my $unikey;
10503: $unikey='parameter_0_'.$name;
1.599 albertel 10504: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10505: $$metathesekeys{$unikey}=1;
1.599 albertel 10506: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10507: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10508: }
1.599 albertel 10509: if (defined($metaentry{':'.$unikey.'.default'})) {
10510: $metaentry{':'.$unikey}=
10511: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10512: }
10513: }
10514:
1.261 albertel 10515: sub metadata_generate_part0 {
10516: my ($metadata,$metacache,$uri) = @_;
10517: my %allnames;
1.737 albertel 10518: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10519: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10520: my $part=$$metacache{':'.$metakey.'.part'};
10521: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10522: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10523: $allnames{$name}=$part;
10524: }
10525: }
10526: }
10527: foreach my $name (keys(%allnames)) {
10528: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10529: my $key=":parameter_0_$name";
1.261 albertel 10530: $$metacache{"$key.part"}='0';
10531: $$metacache{"$key.name"}=$name;
1.428 albertel 10532: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10533: $allnames{$name}.'_'.$name.
10534: '.type'};
1.428 albertel 10535: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10536: '.display'};
1.644 www 10537: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10538: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10539: $$metacache{"$key.display"}=$olddis;
10540: }
1.71 www 10541: }
10542:
1.764 albertel 10543: # ------------------------------------------------------ Devalidate title cache
10544:
10545: sub devalidate_title_cache {
10546: my ($url)=@_;
10547: if (!$env{'request.course.id'}) { return; }
10548: my $symb=&symbread($url);
10549: if (!$symb) { return; }
10550: my $key=$env{'request.course.id'}."\0".$symb;
10551: &devalidate_cache_new('title',$key);
10552: }
10553:
1.1014 droeschl 10554: # ------------------------------------------------- Get the title of a course
10555:
10556: sub current_course_title {
10557: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10558: }
1.301 www 10559: # ------------------------------------------------- Get the title of a resource
10560:
10561: sub gettitle {
10562: my $urlsymb=shift;
10563: my $symb=&symbread($urlsymb);
1.534 albertel 10564: if ($symb) {
1.620 albertel 10565: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10566: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10567: if (defined($cached)) {
10568: return $result;
10569: }
1.534 albertel 10570: my ($map,$resid,$url)=&decode_symb($symb);
10571: my $title='';
1.907 albertel 10572: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10573: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10574: } else {
10575: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10576: &GDBM_READER(),0640)) {
10577: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10578: $title=$bighash{'title_'.$mapid.'.'.$resid};
10579: untie(%bighash);
10580: }
1.534 albertel 10581: }
10582: $title=~s/\&colon\;/\:/gs;
10583: if ($title) {
1.1159 www 10584: # Remember both $symb and $title for dynamic metadata
10585: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10586: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10587: # Cache this title and then return it
1.599 albertel 10588: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10589: }
10590: $urlsymb=$url;
10591: }
10592: my $title=&metadata($urlsymb,'title');
10593: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10594: return $title;
1.301 www 10595: }
1.613 albertel 10596:
1.614 albertel 10597: sub get_slot {
10598: my ($which,$cnum,$cdom)=@_;
10599: if (!$cnum || !$cdom) {
1.790 albertel 10600: (undef,my $courseid)=&whichuser();
1.620 albertel 10601: $cdom=$env{'course.'.$courseid.'.domain'};
10602: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10603: }
1.703 albertel 10604: my $key=join("\0",'slots',$cdom,$cnum,$which);
10605: my %slotinfo;
10606: if (exists($remembered{$key})) {
10607: $slotinfo{$which} = $remembered{$key};
10608: } else {
10609: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10610: &Apache::lonhomework::showhash(%slotinfo);
10611: my ($tmp)=keys(%slotinfo);
10612: if ($tmp=~/^error:/) { return (); }
10613: $remembered{$key} = $slotinfo{$which};
10614: }
1.616 albertel 10615: if (ref($slotinfo{$which}) eq 'HASH') {
10616: return %{$slotinfo{$which}};
10617: }
10618: return $slotinfo{$which};
1.614 albertel 10619: }
1.1150 raeburn 10620:
10621: sub get_reservable_slots {
10622: my ($cnum,$cdom,$uname,$udom) = @_;
10623: my $now = time;
10624: my $reservable_info;
10625: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10626: if (exists($remembered{$key})) {
10627: $reservable_info = $remembered{$key};
10628: } else {
10629: my %resv;
10630: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10631: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10632: $reservable_info = \%resv;
10633: $remembered{$key} = $reservable_info;
10634: }
10635: return $reservable_info;
10636: }
10637:
10638: sub get_course_slots {
10639: my ($cnum,$cdom) = @_;
10640: my $hashid=$cnum.':'.$cdom;
10641: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10642: if (defined($cached)) {
10643: if (ref($result) eq 'HASH') {
10644: return %{$result};
10645: }
10646: } else {
10647: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10648: my ($tmp) = keys(%slots);
10649: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 10650: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10651: return %slots;
10652: }
10653: }
10654: return;
10655: }
10656:
10657: sub devalidate_slots_cache {
10658: my ($cnum,$cdom)=@_;
10659: my $hashid=$cnum.':'.$cdom;
10660: &devalidate_cache_new('allslots',$hashid);
10661: }
10662:
1.1172.2.8 raeburn 10663: sub get_coursechange {
10664: my ($cdom,$cnum) = @_;
10665: if ($cdom eq '' || $cnum eq '') {
10666: return unless ($env{'request.course.id'});
10667: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10668: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10669: }
10670: my $hashid=$cdom.'_'.$cnum;
10671: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10672: if ((defined($cached)) && ($change ne '')) {
10673: return $change;
10674: } else {
10675: my %crshash;
10676: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10677: if ($crshash{'internal.contentchange'} eq '') {
10678: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10679: if ($change eq '') {
10680: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10681: $change = $crshash{'internal.created'};
10682: }
10683: } else {
10684: $change = $crshash{'internal.contentchange'};
10685: }
10686: my $cachetime = 600;
10687: &do_cache_new('crschange',$hashid,$change,$cachetime);
10688: }
10689: return $change;
10690: }
10691:
10692: sub devalidate_coursechange_cache {
10693: my ($cnum,$cdom)=@_;
10694: my $hashid=$cnum.':'.$cdom;
10695: &devalidate_cache_new('crschange',$hashid);
10696: }
10697:
1.31 www 10698: # ------------------------------------------------- Update symbolic store links
10699:
10700: sub symblist {
10701: my ($mapname,%newhash)=@_;
1.438 www 10702: $mapname=&deversion(&declutter($mapname));
1.31 www 10703: my %hash;
1.620 albertel 10704: if (($env{'request.course.fn'}) && (%newhash)) {
10705: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10706: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10707: foreach my $url (keys(%newhash)) {
1.711 albertel 10708: next if ($url eq 'last_known'
10709: && $env{'form.no_update_last_known'});
10710: $hash{declutter($url)}=&encode_symb($mapname,
10711: $newhash{$url}->[1],
10712: $newhash{$url}->[0]);
1.191 harris41 10713: }
1.31 www 10714: if (untie(%hash)) {
10715: return 'ok';
10716: }
10717: }
10718: }
10719: return 'error';
1.212 www 10720: }
10721:
10722: # --------------------------------------------------------------- Verify a symb
10723:
10724: sub symbverify {
1.1172.2.11 raeburn 10725: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10726: my $thisfn=$thisurl;
1.439 www 10727: $thisfn=&declutter($thisfn);
1.215 www 10728: # direct jump to resource in page or to a sequence - will construct own symbs
10729: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10730: # check URL part
1.409 www 10731: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10732:
1.431 www 10733: unless ($url eq $thisfn) { return 0; }
1.213 www 10734:
1.216 www 10735: $symb=&symbclean($symb);
1.510 www 10736: $thisurl=&deversion($thisurl);
1.439 www 10737: $thisfn=&deversion($thisfn);
1.213 www 10738:
10739: my %bighash;
10740: my $okay=0;
1.431 www 10741:
1.620 albertel 10742: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10743: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 10744: my $noclutter;
1.1032 raeburn 10745: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10746: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 10747: if ($map =~ m{^uploaded/.+\.page$}) {
10748: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10749: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10750: $noclutter = 1;
10751: }
10752: }
10753: my $ids;
10754: if ($noclutter) {
10755: $ids=$bighash{'ids_'.$thisurl};
10756: } else {
10757: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10758: }
1.1102 raeburn 10759: unless ($ids) {
1.1172.2.13 raeburn 10760: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 10761: $ids=$bighash{$idkey};
1.216 www 10762: }
10763: if ($ids) {
10764: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 10765: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10766: $symb =~ s/\?.+$//;
10767: }
1.800 albertel 10768: foreach my $id (split(/\,/,$ids)) {
10769: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10770: if (
10771: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 10772: eq $symb) {
1.1172.2.11 raeburn 10773: if (ref($encstate)) {
10774: $$encstate = $bighash{'encrypted_'.$id};
10775: }
1.1172.2.13 raeburn 10776: if (($env{'request.role.adv'}) ||
10777: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 10778: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 10779: $okay=1;
10780: last;
10781: }
10782: }
10783: }
1.216 www 10784: }
1.213 www 10785: untie(%bighash);
10786: }
10787: return $okay;
1.31 www 10788: }
10789:
1.210 www 10790: # --------------------------------------------------------------- Clean-up symb
10791:
10792: sub symbclean {
10793: my $symb=shift;
1.568 albertel 10794: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10795: # remove version from map
10796: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10797:
1.210 www 10798: # remove version from URL
10799: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10800:
1.507 www 10801: # remove wrapper
10802:
1.510 www 10803: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10804: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10805: return $symb;
1.409 www 10806: }
10807:
10808: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10809:
10810: sub encode_symb {
10811: my ($map,$resid,$url)=@_;
10812: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10813: }
1.409 www 10814:
10815: sub decode_symb {
1.568 albertel 10816: my $symb=shift;
10817: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10818: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10819: return (&fixversion($map),$resid,&fixversion($url));
10820: }
10821:
10822: sub fixversion {
10823: my $fn=shift;
1.609 banghart 10824: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10825: my %bighash;
10826: my $uri=&clutter($fn);
1.620 albertel 10827: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10828: # is this cached?
1.599 albertel 10829: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10830: if (defined($cached)) { return $result; }
10831: # unfortunately not cached, or expired
1.620 albertel 10832: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10833: &GDBM_READER(),0640)) {
10834: if ($bighash{'version_'.$uri}) {
10835: my $version=$bighash{'version_'.$uri};
1.444 www 10836: unless (($version eq 'mostrecent') ||
10837: ($version==&getversion($uri))) {
1.440 www 10838: $uri=~s/\.(\w+)$/\.$version\.$1/;
10839: }
10840: }
10841: untie %bighash;
1.413 www 10842: }
1.599 albertel 10843: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10844: }
10845:
10846: sub deversion {
10847: my $url=shift;
10848: $url=~s/\.\d+\.(\w+)$/\.$1/;
10849: return $url;
1.210 www 10850: }
10851:
1.31 www 10852: # ------------------------------------------------------ Return symb list entry
10853:
10854: sub symbread {
1.249 www 10855: my ($thisfn,$donotrecurse)=@_;
1.1172.2.13 raeburn 10856: my $cache_str;
10857: if ($thisfn ne '') {
10858: $cache_str='request.symbread.cached.'.$thisfn;
10859: if ($env{$cache_str} ne '') {
1.1172.2.8 raeburn 10860: return $env{$cache_str};
10861: }
1.1172.2.13 raeburn 10862: } else {
1.242 www 10863: # no filename provided? try from environment
1.620 albertel 10864: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 10865: return $env{$cache_str}=&symbclean($env{'request.symb'});
10866: }
10867: $thisfn=$env{'request.filename'};
1.44 www 10868: }
1.569 albertel 10869: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10870: # is that filename actually a symb? Verify, clean, and return
10871: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10872: if (&symbverify($thisfn,$1)) {
1.620 albertel 10873: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10874: }
1.242 www 10875: }
1.44 www 10876: $thisfn=declutter($thisfn);
1.31 www 10877: my %hash;
1.37 www 10878: my %bighash;
10879: my $syval='';
1.620 albertel 10880: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10881: my $targetfn = $thisfn;
1.609 banghart 10882: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10883: $targetfn = 'adm/wrapper/'.$thisfn;
10884: }
1.687 albertel 10885: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10886: $targetfn=$1;
10887: }
1.620 albertel 10888: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10889: &GDBM_READER(),0640)) {
1.481 raeburn 10890: $syval=$hash{$targetfn};
1.37 www 10891: untie(%hash);
10892: }
10893: # ---------------------------------------------------------- There was an entry
10894: if ($syval) {
1.601 albertel 10895: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10896: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10897: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10898: #return $env{$cache_str}='';
1.601 albertel 10899: #}
10900: #$syval.=$1;
10901: #}
1.37 www 10902: } else {
10903: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10904: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10905: &GDBM_READER(),0640)) {
1.37 www 10906: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10907: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10908: unless ($ids) {
10909: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10910: }
10911: unless ($ids) {
10912: # alias?
10913: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10914: }
1.37 www 10915: if ($ids) {
10916: # ------------------------------------------------------------------- Has ID(s)
10917: my @possibilities=split(/\,/,$ids);
1.39 www 10918: if ($#possibilities==0) {
10919: # ----------------------------------------------- There is only one possibility
1.37 www 10920: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10921: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10922: $resid,$thisfn);
1.249 www 10923: } elsif (!$donotrecurse) {
1.39 www 10924: # ------------------------------------------ There is more than one possibility
10925: my $realpossible=0;
1.800 albertel 10926: foreach my $id (@possibilities) {
10927: my $file=$bighash{'src_'.$id};
1.39 www 10928: if (&allowed('bre',$file)) {
1.800 albertel 10929: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10930: if ($bighash{'map_type_'.$mapid} ne 'page') {
10931: $realpossible++;
1.626 albertel 10932: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10933: $resid,$thisfn);
1.39 www 10934: }
10935: }
1.191 harris41 10936: }
1.39 www 10937: if ($realpossible!=1) { $syval=''; }
1.249 www 10938: } else {
10939: $syval='';
1.37 www 10940: }
10941: }
10942: untie(%bighash)
1.481 raeburn 10943: }
1.31 www 10944: }
1.62 www 10945: if ($syval) {
1.620 albertel 10946: return $env{$cache_str}=$syval;
1.62 www 10947: }
1.31 www 10948: }
1.949 raeburn 10949: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10950: return $env{$cache_str}='';
1.31 www 10951: }
10952:
10953: # ---------------------------------------------------------- Return random seed
10954:
1.32 www 10955: sub numval {
10956: my $txt=shift;
10957: $txt=~tr/A-J/0-9/;
10958: $txt=~tr/a-j/0-9/;
10959: $txt=~tr/K-T/0-9/;
10960: $txt=~tr/k-t/0-9/;
10961: $txt=~tr/U-Z/0-5/;
10962: $txt=~tr/u-z/0-5/;
10963: $txt=~s/\D//g;
1.564 albertel 10964: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10965: return int($txt);
1.368 albertel 10966: }
10967:
1.484 albertel 10968: sub numval2 {
10969: my $txt=shift;
10970: $txt=~tr/A-J/0-9/;
10971: $txt=~tr/a-j/0-9/;
10972: $txt=~tr/K-T/0-9/;
10973: $txt=~tr/k-t/0-9/;
10974: $txt=~tr/U-Z/0-5/;
10975: $txt=~tr/u-z/0-5/;
10976: $txt=~s/\D//g;
10977: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10978: my $total;
10979: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10980: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10981: return int($total);
10982: }
10983:
1.575 albertel 10984: sub numval3 {
10985: use integer;
10986: my $txt=shift;
10987: $txt=~tr/A-J/0-9/;
10988: $txt=~tr/a-j/0-9/;
10989: $txt=~tr/K-T/0-9/;
10990: $txt=~tr/k-t/0-9/;
10991: $txt=~tr/U-Z/0-5/;
10992: $txt=~tr/u-z/0-5/;
10993: $txt=~s/\D//g;
10994: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10995: my $total;
10996: foreach my $val (@txts) { $total+=$val; }
10997: if ($_64bit) { $total=(($total<<32)>>32); }
10998: return $total;
10999: }
11000:
1.675 albertel 11001: sub digest {
11002: my ($data)=@_;
11003: my $digest=&Digest::MD5::md5($data);
11004: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11005: my ($e,$f);
11006: {
11007: use integer;
11008: $e=($a+$b);
11009: $f=($c+$d);
11010: if ($_64bit) {
11011: $e=(($e<<32)>>32);
11012: $f=(($f<<32)>>32);
11013: }
11014: }
11015: if (wantarray) {
11016: return ($e,$f);
11017: } else {
11018: my $g;
11019: {
11020: use integer;
11021: $g=($e+$f);
11022: if ($_64bit) {
11023: $g=(($g<<32)>>32);
11024: }
11025: }
11026: return $g;
11027: }
11028: }
11029:
1.368 albertel 11030: sub latest_rnd_algorithm_id {
1.675 albertel 11031: return '64bit5';
1.366 albertel 11032: }
1.32 www 11033:
1.503 albertel 11034: sub get_rand_alg {
11035: my ($courseid)=@_;
1.790 albertel 11036: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11037: if ($courseid) {
1.620 albertel 11038: return $env{"course.$courseid.rndseed"};
1.503 albertel 11039: }
11040: return &latest_rnd_algorithm_id();
11041: }
11042:
1.562 albertel 11043: sub validCODE {
11044: my ($CODE)=@_;
11045: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11046: return 0;
11047: }
11048:
1.491 albertel 11049: sub getCODE {
1.620 albertel 11050: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11051: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11052: defined($Apache::lonhomework::parsing_a_task) ) &&
11053: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11054: return $Apache::lonhomework::history{'resource.CODE'};
11055: }
11056: return undef;
11057: }
1.1133 foxr 11058: #
11059: # Determines the random seed for a specific context:
11060: #
11061: # parameters:
11062: # symb - in course context the symb for the seed.
11063: # course_id - The course id of the form domain_coursenum.
11064: # domain - Domain for the user.
11065: # course - Course for the user.
11066: # cenv - environment of the course.
11067: #
11068: # NOTE:
11069: # All parameters are picked out of the environment if missing
11070: # or not defined.
11071: # If a symb cannot be determined the current time is used instead.
11072: #
11073: # For a given well defined symb, courside, domain, username,
11074: # and course environment, the seed is reproducible.
11075: #
1.31 www 11076: sub rndseed {
1.1133 foxr 11077: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11078: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11079: if (!defined($symb)) {
1.366 albertel 11080: unless ($symb=$wsymb) { return time; }
11081: }
1.1146 foxr 11082: if (!defined $courseid) {
11083: $courseid=$wcourseid;
11084: }
11085: if (!defined $domain) { $domain=$wdomain; }
11086: if (!defined $username) { $username=$wusername }
1.1133 foxr 11087:
11088: my $which;
11089: if (defined($cenv->{'rndseed'})) {
11090: $which = $cenv->{'rndseed'};
11091: } else {
11092: $which =&get_rand_alg($courseid);
11093: }
1.491 albertel 11094: if (defined(&getCODE())) {
1.675 albertel 11095: if ($which eq '64bit5') {
11096: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11097: } elsif ($which eq '64bit4') {
1.575 albertel 11098: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11099: } else {
11100: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11101: }
1.675 albertel 11102: } elsif ($which eq '64bit5') {
11103: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11104: } elsif ($which eq '64bit4') {
11105: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11106: } elsif ($which eq '64bit3') {
11107: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11108: } elsif ($which eq '64bit2') {
11109: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11110: } elsif ($which eq '64bit') {
11111: return &rndseed_64bit($symb,$courseid,$domain,$username);
11112: }
11113: return &rndseed_32bit($symb,$courseid,$domain,$username);
11114: }
11115:
11116: sub rndseed_32bit {
11117: my ($symb,$courseid,$domain,$username)=@_;
11118: {
11119: use integer;
11120: my $symbchck=unpack("%32C*",$symb) << 27;
11121: my $symbseed=numval($symb) << 22;
11122: my $namechck=unpack("%32C*",$username) << 17;
11123: my $nameseed=numval($username) << 12;
11124: my $domainseed=unpack("%32C*",$domain) << 7;
11125: my $courseseed=unpack("%32C*",$courseid);
11126: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11127: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11128: #&logthis("rndseed :$num:$symb");
1.564 albertel 11129: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11130: return $num;
11131: }
11132: }
11133:
11134: sub rndseed_64bit {
11135: my ($symb,$courseid,$domain,$username)=@_;
11136: {
11137: use integer;
11138: my $symbchck=unpack("%32S*",$symb) << 21;
11139: my $symbseed=numval($symb) << 10;
11140: my $namechck=unpack("%32S*",$username);
11141:
11142: my $nameseed=numval($username) << 21;
11143: my $domainseed=unpack("%32S*",$domain) << 10;
11144: my $courseseed=unpack("%32S*",$courseid);
11145:
11146: my $num1=$symbchck+$symbseed+$namechck;
11147: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11148: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11149: #&logthis("rndseed :$num:$symb");
1.564 albertel 11150: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11151: return "$num1,$num2";
1.155 albertel 11152: }
1.366 albertel 11153: }
11154:
1.443 albertel 11155: sub rndseed_64bit2 {
11156: my ($symb,$courseid,$domain,$username)=@_;
11157: {
11158: use integer;
11159: # strings need to be an even # of cahracters long, it it is odd the
11160: # last characters gets thrown away
11161: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11162: my $symbseed=numval($symb) << 10;
11163: my $namechck=unpack("%32S*",$username.' ');
11164:
11165: my $nameseed=numval($username) << 21;
1.501 albertel 11166: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11167: my $courseseed=unpack("%32S*",$courseid.' ');
11168:
11169: my $num1=$symbchck+$symbseed+$namechck;
11170: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11171: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11172: #&logthis("rndseed :$num:$symb");
1.803 albertel 11173: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11174: return "$num1,$num2";
11175: }
11176: }
11177:
11178: sub rndseed_64bit3 {
11179: my ($symb,$courseid,$domain,$username)=@_;
11180: {
11181: use integer;
11182: # strings need to be an even # of cahracters long, it it is odd the
11183: # last characters gets thrown away
11184: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11185: my $symbseed=numval2($symb) << 10;
11186: my $namechck=unpack("%32S*",$username.' ');
11187:
11188: my $nameseed=numval2($username) << 21;
1.443 albertel 11189: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11190: my $courseseed=unpack("%32S*",$courseid.' ');
11191:
11192: my $num1=$symbchck+$symbseed+$namechck;
11193: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11194: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11195: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11196: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11197:
1.503 albertel 11198: return "$num1:$num2";
1.443 albertel 11199: }
11200: }
11201:
1.575 albertel 11202: sub rndseed_64bit4 {
11203: my ($symb,$courseid,$domain,$username)=@_;
11204: {
11205: use integer;
11206: # strings need to be an even # of cahracters long, it it is odd the
11207: # last characters gets thrown away
11208: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11209: my $symbseed=numval3($symb) << 10;
11210: my $namechck=unpack("%32S*",$username.' ');
11211:
11212: my $nameseed=numval3($username) << 21;
11213: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11214: my $courseseed=unpack("%32S*",$courseid.' ');
11215:
11216: my $num1=$symbchck+$symbseed+$namechck;
11217: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11218: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11219: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11220: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11221:
1.575 albertel 11222: return "$num1:$num2";
11223: }
11224: }
11225:
1.675 albertel 11226: sub rndseed_64bit5 {
11227: my ($symb,$courseid,$domain,$username)=@_;
11228: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11229: return "$num1:$num2";
11230: }
11231:
1.366 albertel 11232: sub rndseed_CODE_64bit {
11233: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11234: {
1.366 albertel 11235: use integer;
1.443 albertel 11236: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11237: my $symbseed=numval2($symb);
1.491 albertel 11238: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11239: my $CODEseed=numval(&getCODE());
1.443 albertel 11240: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11241: my $num1=$symbseed+$CODEchck;
11242: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11243: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11244: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11245: if ($_64bit) { $num1=(($num1<<32)>>32); }
11246: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11247: return "$num1:$num2";
1.366 albertel 11248: }
11249: }
11250:
1.575 albertel 11251: sub rndseed_CODE_64bit4 {
11252: my ($symb,$courseid,$domain,$username)=@_;
11253: {
11254: use integer;
11255: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11256: my $symbseed=numval3($symb);
11257: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11258: my $CODEseed=numval3(&getCODE());
11259: my $courseseed=unpack("%32S*",$courseid.' ');
11260: my $num1=$symbseed+$CODEchck;
11261: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11262: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11263: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11264: if ($_64bit) { $num1=(($num1<<32)>>32); }
11265: if ($_64bit) { $num2=(($num2<<32)>>32); }
11266: return "$num1:$num2";
11267: }
11268: }
11269:
1.675 albertel 11270: sub rndseed_CODE_64bit5 {
11271: my ($symb,$courseid,$domain,$username)=@_;
11272: my $code = &getCODE();
11273: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11274: return "$num1:$num2";
11275: }
11276:
1.366 albertel 11277: sub setup_random_from_rndseed {
11278: my ($rndseed)=@_;
1.503 albertel 11279: if ($rndseed =~/([,:])/) {
11280: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 11281: &Math::Random::random_set_seed(abs($num1),abs($num2));
11282: } else {
11283: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11284: }
1.36 albertel 11285: }
11286:
1.474 albertel 11287: sub latest_receipt_algorithm_id {
1.835 albertel 11288: return 'receipt3';
1.474 albertel 11289: }
11290:
1.480 www 11291: sub recunique {
11292: my $fucourseid=shift;
11293: my $unique;
1.835 albertel 11294: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11295: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11296: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11297: } else {
11298: $unique=$perlvar{'lonReceipt'};
11299: }
11300: return unpack("%32C*",$unique);
11301: }
11302:
11303: sub recprefix {
11304: my $fucourseid=shift;
11305: my $prefix;
1.835 albertel 11306: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11307: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11308: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11309: } else {
11310: $prefix=$perlvar{'lonHostID'};
11311: }
11312: return unpack("%32C*",$prefix);
11313: }
11314:
1.76 www 11315: sub ireceipt {
1.474 albertel 11316: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11317:
11318: my $return =&recprefix($fucourseid).'-';
11319:
11320: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11321: $env{'request.state'} eq 'construct') {
11322: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11323: return $return;
11324: }
11325:
1.76 www 11326: my $cuname=unpack("%32C*",$funame);
11327: my $cudom=unpack("%32C*",$fudom);
11328: my $cucourseid=unpack("%32C*",$fucourseid);
11329: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11330: my $cunique=&recunique($fucourseid);
1.474 albertel 11331: my $cpart=unpack("%32S*",$part);
1.835 albertel 11332: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11333:
1.790 albertel 11334: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11335:
11336: $return.= ($cunique%$cuname+
11337: $cunique%$cudom+
11338: $cusymb%$cuname+
11339: $cusymb%$cudom+
11340: $cucourseid%$cuname+
11341: $cucourseid%$cudom+
11342: $cpart%$cuname+
11343: $cpart%$cudom);
11344: } else {
11345: $return.= ($cunique%$cuname+
11346: $cunique%$cudom+
11347: $cusymb%$cuname+
11348: $cusymb%$cudom+
11349: $cucourseid%$cuname+
11350: $cucourseid%$cudom);
11351: }
11352: return $return;
1.76 www 11353: }
11354:
11355: sub receipt {
1.474 albertel 11356: my ($part)=@_;
1.790 albertel 11357: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11358: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11359: }
1.260 ng 11360:
1.790 albertel 11361: sub whichuser {
11362: my ($passedsymb)=@_;
11363: my ($symb,$courseid,$domain,$name,$publicuser);
11364: if (defined($env{'form.grade_symb'})) {
11365: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11366: my $allowed=&allowed('vgr',$tmp_courseid);
11367: if (!$allowed &&
11368: exists($env{'request.course.sec'}) &&
11369: $env{'request.course.sec'} !~ /^\s*$/) {
11370: $allowed=&allowed('vgr',$tmp_courseid.
11371: '/'.$env{'request.course.sec'});
11372: }
11373: if ($allowed) {
11374: ($symb)=&get_env_multiple('form.grade_symb');
11375: $courseid=$tmp_courseid;
11376: ($domain)=&get_env_multiple('form.grade_domain');
11377: ($name)=&get_env_multiple('form.grade_username');
11378: return ($symb,$courseid,$domain,$name,$publicuser);
11379: }
11380: }
11381: if (!$passedsymb) {
11382: $symb=&symbread();
11383: } else {
11384: $symb=$passedsymb;
11385: }
11386: $courseid=$env{'request.course.id'};
11387: $domain=$env{'user.domain'};
11388: $name=$env{'user.name'};
11389: if ($name eq 'public' && $domain eq 'public') {
11390: if (!defined($env{'form.username'})) {
11391: $env{'form.username'}.=time.rand(10000000);
11392: }
11393: $name.=$env{'form.username'};
11394: }
11395: return ($symb,$courseid,$domain,$name,$publicuser);
11396:
11397: }
11398:
1.36 albertel 11399: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11400: # returns either the contents of the file or
11401: # -1 if the file doesn't exist
1.481 raeburn 11402: #
11403: # if the target is a file that was uploaded via DOCS,
11404: # a check will be made to see if a current copy exists on the local server,
11405: # if it does this will be served, otherwise a copy will be retrieved from
11406: # the home server for the course and stored in /home/httpd/html/userfiles on
11407: # the local server.
1.472 albertel 11408:
1.36 albertel 11409: sub getfile {
1.538 albertel 11410: my ($file) = @_;
1.609 banghart 11411: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11412: &repcopy($file);
11413: return &readfile($file);
11414: }
11415:
11416: sub repcopy_userfile {
11417: my ($file)=@_;
1.1142 raeburn 11418: my $londocroot = $perlvar{'lonDocRoot'};
11419: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11420: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11421: my ($cdom,$cnum,$filename) =
1.811 albertel 11422: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11423: my $uri="/uploaded/$cdom/$cnum/$filename";
11424: if (-e "$file") {
1.828 www 11425: # we already have a local copy, check it out
1.538 albertel 11426: my @fileinfo = stat($file);
1.828 www 11427: my $rtncode;
11428: my $info;
1.538 albertel 11429: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11430: if ($lwpresp ne 'ok') {
1.828 www 11431: # there is no such file anymore, even though we had a local copy
1.482 albertel 11432: if ($rtncode eq '404') {
1.538 albertel 11433: unlink($file);
1.482 albertel 11434: }
11435: return -1;
11436: }
11437: if ($info < $fileinfo[9]) {
1.828 www 11438: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11439: return 'ok';
1.828 www 11440: } else {
11441: # the file is outdated, get rid of it
11442: unlink($file);
1.482 albertel 11443: }
1.828 www 11444: }
11445: # one way or the other, at this point, we don't have the file
11446: # construct the correct path for the file
11447: my @parts = ($cdom,$cnum);
11448: if ($filename =~ m|^(.+)/[^/]+$|) {
11449: push @parts, split(/\//,$1);
11450: }
11451: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11452: foreach my $part (@parts) {
11453: $path .= '/'.$part;
11454: if (!-e $path) {
11455: mkdir($path,0770);
1.482 albertel 11456: }
11457: }
1.828 www 11458: # now the path exists for sure
11459: # get a user agent
11460: my $ua=new LWP::UserAgent;
11461: my $transferfile=$file.'.in.transfer';
11462: # FIXME: this should flock
11463: if (-e $transferfile) { return 'ok'; }
11464: my $request;
11465: $uri=~s/^\///;
1.980 raeburn 11466: my $homeserver = &homeserver($cnum,$cdom);
11467: my $protocol = $protocol{$homeserver};
11468: $protocol = 'http' if ($protocol ne 'https');
11469: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11470: my $response=$ua->request($request,$transferfile);
11471: # did it work?
11472: if ($response->is_error()) {
11473: unlink($transferfile);
11474: &logthis("Userfile repcopy failed for $uri");
11475: return -1;
11476: }
11477: # worked, rename the transfer file
11478: rename($transferfile,$file);
1.607 raeburn 11479: return 'ok';
1.481 raeburn 11480: }
11481:
1.517 albertel 11482: sub tokenwrapper {
11483: my $uri=shift;
1.980 raeburn 11484: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11485: $uri=~s|^/||;
1.620 albertel 11486: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11487: my $token=$1;
1.552 albertel 11488: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11489: if ($udom && $uname && $file) {
11490: $file=~s|(\?\.*)*$||;
1.949 raeburn 11491: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11492: my $homeserver = &homeserver($uname,$udom);
11493: my $protocol = $protocol{$homeserver};
11494: $protocol = 'http' if ($protocol ne 'https');
11495: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11496: (($uri=~/\?/)?'&':'?').'token='.$token.
11497: '&tokenissued='.$perlvar{'lonHostID'};
11498: } else {
11499: return '/adm/notfound.html';
11500: }
11501: }
11502:
1.828 www 11503: # call with reqtype HEAD: get last modification time
11504: # call with reqtype GET: get the file contents
11505: # Do not call this with reqtype GET for large files! It loads everything into memory
11506: #
1.481 raeburn 11507: sub getuploaded {
11508: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11509: $uri=~s/^\///;
1.980 raeburn 11510: my $homeserver = &homeserver($cnum,$cdom);
11511: my $protocol = $protocol{$homeserver};
11512: $protocol = 'http' if ($protocol ne 'https');
11513: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11514: my $ua=new LWP::UserAgent;
11515: my $request=new HTTP::Request($reqtype,$uri);
11516: my $response=$ua->request($request);
11517: $$rtncode = $response->code;
1.482 albertel 11518: if (! $response->is_success()) {
11519: return 'failed';
11520: }
11521: if ($reqtype eq 'HEAD') {
1.486 www 11522: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11523: } elsif ($reqtype eq 'GET') {
11524: $$info = $response->content;
1.472 albertel 11525: }
1.482 albertel 11526: return 'ok';
1.36 albertel 11527: }
11528:
1.481 raeburn 11529: sub readfile {
11530: my $file = shift;
11531: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11532: my $fh;
11533: open($fh,"<$file");
11534: my $a='';
1.800 albertel 11535: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11536: return $a;
11537: }
11538:
1.36 albertel 11539: sub filelocation {
1.590 banghart 11540: my ($dir,$file) = @_;
11541: my $location;
11542: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11543:
11544: if ($file =~ m-^/adm/-) {
11545: $file=~s-^/adm/wrapper/-/-;
11546: $file=~s-^/adm/coursedocs/showdoc/-/-;
11547: }
1.882 albertel 11548:
1.1139 www 11549: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11550: $location = $file;
1.609 banghart 11551: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11552: my ($udom,$uname,$filename)=
1.811 albertel 11553: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11554: my $home=&homeserver($uname,$udom);
11555: my $is_me=0;
11556: my @ids=¤t_machine_ids();
11557: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11558: if ($is_me) {
1.1117 foxr 11559: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11560: } else {
11561: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11562: $udom.'/'.$uname.'/'.$filename;
11563: }
1.882 albertel 11564: } elsif ($file =~ m-^/adm/-) {
11565: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11566: } else {
11567: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11568: $file=~s:^/(res|priv)/:/:;
11569: my $space=$1;
1.590 banghart 11570: if ( !( $file =~ m:^/:) ) {
11571: $location = $dir. '/'.$file;
11572: } else {
1.1142 raeburn 11573: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11574: }
1.59 albertel 11575: }
1.590 banghart 11576: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11577: while ($location=~m{/\.\./}) {
11578: if ($location =~ m{/[^/]+/\.\./}) {
11579: $location=~ s{/[^/]+/\.\./}{/}g;
11580: } else {
11581: $location=~ s{/\.\./}{/}g;
11582: }
11583: } #remove dir/..
1.590 banghart 11584: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11585: return $location;
1.46 www 11586: }
1.36 albertel 11587:
1.46 www 11588: sub hreflocation {
11589: my ($dir,$file)=@_;
1.980 raeburn 11590: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11591: $file=filelocation($dir,$file);
1.700 albertel 11592: } elsif ($file=~m-^/adm/-) {
11593: $file=~s-^/adm/wrapper/-/-;
11594: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11595: }
11596: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11597: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11598: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11599: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11600: {/uploaded/$1/$2/}x;
1.46 www 11601: }
1.913 albertel 11602: if ($file=~ m{^/userfiles/}) {
11603: $file =~ s{^/userfiles/}{/uploaded/};
11604: }
1.462 albertel 11605: return $file;
1.465 albertel 11606: }
11607:
1.1139 www 11608:
11609:
11610:
11611:
1.465 albertel 11612: sub current_machine_domains {
1.853 albertel 11613: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11614: }
11615:
11616: sub machine_domains {
11617: my ($hostname) = @_;
1.465 albertel 11618: my @domains;
1.838 albertel 11619: my %hostname = &all_hostnames();
1.465 albertel 11620: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11621: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11622: if ($hostname eq $name) {
1.844 albertel 11623: push(@domains,&host_domain($id));
1.465 albertel 11624: }
11625: }
11626: return @domains;
11627: }
11628:
11629: sub current_machine_ids {
1.853 albertel 11630: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11631: }
11632:
11633: sub machine_ids {
11634: my ($hostname) = @_;
11635: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11636: my @ids;
1.888 albertel 11637: my %name_to_host = &all_names();
1.889 albertel 11638: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11639: return @{ $name_to_host{$hostname} };
11640: }
11641: return;
1.31 www 11642: }
11643:
1.824 raeburn 11644: sub additional_machine_domains {
11645: my @domains;
11646: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11647: while( my $line = <$fh>) {
11648: $line =~ s/\s//g;
11649: push(@domains,$line);
11650: }
11651: return @domains;
11652: }
11653:
11654: sub default_login_domain {
11655: my $domain = $perlvar{'lonDefDomain'};
11656: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11657: foreach my $posdom (¤t_machine_domains(),
11658: &additional_machine_domains()) {
11659: if (lc($posdom) eq lc($testdomain)) {
11660: $domain=$posdom;
11661: last;
11662: }
11663: }
11664: return $domain;
11665: }
11666:
1.31 www 11667: # ------------------------------------------------------------- Declutters URLs
11668:
11669: sub declutter {
11670: my $thisfn=shift;
1.569 albertel 11671: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 11672: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 11673: $thisfn=~s/^\///;
1.697 albertel 11674: $thisfn=~s|^adm/wrapper/||;
11675: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11676: $thisfn=~s/^res\///;
1.1172 bisitz 11677: $thisfn=~s/^priv\///;
1.1032 raeburn 11678: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11679: $thisfn=~s/\?.+$//;
11680: }
1.268 www 11681: return $thisfn;
11682: }
11683:
11684: # ------------------------------------------------------------- Clutter up URLs
11685:
11686: sub clutter {
11687: my $thisfn='/'.&declutter(shift);
1.887 albertel 11688: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11689: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11690: $thisfn='/res'.$thisfn;
11691: }
1.1031 raeburn 11692: if ($thisfn !~m|^/adm|) {
11693: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11694: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11695: } else {
11696: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11697: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11698: if ($embstyle eq 'ssi'
11699: || ($embstyle eq 'hdn')
11700: || ($embstyle eq 'rat')
11701: || ($embstyle eq 'prv')
11702: || ($embstyle eq 'ign')) {
11703: #do nothing with these
11704: } elsif (($embstyle eq 'img')
1.695 albertel 11705: || ($embstyle eq 'emb')
11706: || ($embstyle eq 'wrp')) {
11707: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11708: } elsif ($embstyle eq 'unk'
11709: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11710: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11711: } else {
1.718 www 11712: # &logthis("Got a blank emb style");
1.695 albertel 11713: }
1.694 albertel 11714: }
11715: }
1.31 www 11716: return $thisfn;
1.12 www 11717: }
11718:
1.787 albertel 11719: sub clutter_with_no_wrapper {
11720: my $uri = &clutter(shift);
11721: if ($uri =~ m-^/adm/-) {
11722: $uri =~ s-^/adm/wrapper/-/-;
11723: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11724: }
11725: return $uri;
11726: }
11727:
1.557 albertel 11728: sub freeze_escape {
11729: my ($value)=@_;
11730: if (ref($value)) {
11731: $value=&nfreeze($value);
11732: return '__FROZEN__'.&escape($value);
11733: }
11734: return &escape($value);
11735: }
11736:
1.11 www 11737:
1.557 albertel 11738: sub thaw_unescape {
11739: my ($value)=@_;
11740: if ($value =~ /^__FROZEN__/) {
11741: substr($value,0,10,undef);
11742: $value=&unescape($value);
11743: return &thaw($value);
11744: }
11745: return &unescape($value);
11746: }
11747:
1.436 albertel 11748: sub correct_line_ends {
11749: my ($result)=@_;
11750: $$result =~s/\r\n/\n/mg;
11751: $$result =~s/\r/\n/mg;
1.415 albertel 11752: }
1.1 albertel 11753: # ================================================================ Main Program
11754:
1.184 www 11755: sub goodbye {
1.204 albertel 11756: &logthis("Starting Shut down");
1.443 albertel 11757: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11758: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11759: #converted
1.599 albertel 11760: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11761: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11762: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11763: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11764: #1.1 only
1.870 albertel 11765: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11766: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11767: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11768: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11769: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11770: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11771: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11772: &flushcourselogs();
11773: &logthis("Shutting down");
11774: }
11775:
1.852 albertel 11776: sub get_dns {
1.1172.2.17 raeburn 11777: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11778: if (!$ignore_cache) {
11779: my ($content,$cached)=
11780: &Apache::lonnet::is_cached_new('dns',$url);
11781: if ($cached) {
1.1172.2.17 raeburn 11782: &$func($content,$hashref);
1.869 albertel 11783: return;
11784: }
11785: }
11786:
11787: my %alldns;
1.852 albertel 11788: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11789: foreach my $dns (<$config>) {
11790: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11791: my $line = $1;
11792: my ($host,$protocol) = split(/:/,$line);
11793: if ($protocol ne 'https') {
11794: $protocol = 'http';
11795: }
11796: $alldns{$host} = $protocol;
1.869 albertel 11797: }
11798: while (%alldns) {
11799: my ($dns) = keys(%alldns);
1.852 albertel 11800: my $ua=new LWP::UserAgent;
1.1134 raeburn 11801: $ua->timeout(30);
1.979 raeburn 11802: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11803: my $response=$ua->request($request);
1.979 raeburn 11804: delete($alldns{$dns});
1.852 albertel 11805: next if ($response->is_error());
11806: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 11807: unless ($nocache) {
1.1172.2.23 raeburn 11808: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 11809: }
11810: &$func(\@content,$hashref);
1.869 albertel 11811: return;
1.852 albertel 11812: }
11813: close($config);
1.871 albertel 11814: my $which = (split('/',$url))[3];
11815: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11816: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11817: my @content = <$config>;
1.1172.2.17 raeburn 11818: &$func(\@content,$hashref);
11819: return;
11820: }
11821:
11822: # ------------------------------------------------------Get DNS checksums file
11823: sub parse_dns_checksums_tab {
11824: my ($lines,$hashref) = @_;
11825: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11826: my $loncaparev = &get_server_loncaparev($machine_dom);
11827: my ($release,$timestamp) = split(/\-/,$loncaparev);
11828: my (%chksum,%revnum);
11829: if (ref($lines) eq 'ARRAY') {
11830: chomp(@{$lines});
1.1172.2.34 raeburn 11831: my $version = shift(@{$lines});
11832: if ($version eq $release) {
1.1172.2.17 raeburn 11833: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 11834: my ($file,$version,$shasum) = split(/,/,$line);
11835: $chksum{$file} = $shasum;
11836: $revnum{$file} = $version;
1.1172.2.17 raeburn 11837: }
11838: if (ref($hashref) eq 'HASH') {
11839: %{$hashref} = (
11840: sums => \%chksum,
11841: versions => \%revnum,
11842: );
11843: }
11844: }
11845: }
1.869 albertel 11846: return;
1.852 albertel 11847: }
1.1172.2.17 raeburn 11848:
11849: sub fetch_dns_checksums {
11850: my %checksums;
1.1172.2.34 raeburn 11851: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11852: my $loncaparev = &get_server_loncaparev($machine_dom);
11853: my ($release,$timestamp) = split(/\-/,$loncaparev);
11854: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 11855: \%checksums);
11856: return \%checksums;
11857: }
11858:
1.327 albertel 11859: # ------------------------------------------------------------ Read domain file
11860: {
1.852 albertel 11861: my $loaded;
1.846 albertel 11862: my %domain;
11863:
1.852 albertel 11864: sub parse_domain_tab {
11865: my ($lines) = @_;
11866: foreach my $line (@$lines) {
11867: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11868:
1.846 albertel 11869: chomp($line);
1.852 albertel 11870: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11871: my %this_domain;
11872: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11873: 'lang_def', 'city', 'longi', 'lati',
11874: 'primary') {
11875: $this_domain{$field} = shift(@elements);
11876: }
11877: $domain{$name} = \%this_domain;
1.852 albertel 11878: }
11879: }
1.864 albertel 11880:
11881: sub reset_domain_info {
11882: undef($loaded);
11883: undef(%domain);
11884: }
11885:
1.852 albertel 11886: sub load_domain_tab {
1.869 albertel 11887: my ($ignore_cache) = @_;
11888: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11889: my $fh;
11890: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11891: my @lines = <$fh>;
11892: &parse_domain_tab(\@lines);
1.448 albertel 11893: }
1.852 albertel 11894: close($fh);
11895: $loaded = 1;
1.327 albertel 11896: }
1.846 albertel 11897:
11898: sub domain {
1.852 albertel 11899: &load_domain_tab() if (!$loaded);
11900:
1.846 albertel 11901: my ($name,$what) = @_;
11902: return if ( !exists($domain{$name}) );
11903:
11904: if (!$what) {
11905: return $domain{$name}{'description'};
11906: }
11907: return $domain{$name}{$what};
11908: }
1.974 raeburn 11909:
11910: sub domain_info {
11911: &load_domain_tab() if (!$loaded);
11912: return %domain;
11913: }
11914:
1.327 albertel 11915: }
11916:
11917:
1.1 albertel 11918: # ------------------------------------------------------------- Read hosts file
11919: {
1.838 albertel 11920: my %hostname;
1.844 albertel 11921: my %hostdom;
1.845 albertel 11922: my %libserv;
1.852 albertel 11923: my $loaded;
1.888 albertel 11924: my %name_to_host;
1.1074 raeburn 11925: my %internetdom;
1.1107 raeburn 11926: my %LC_dns_serv;
1.852 albertel 11927:
11928: sub parse_hosts_tab {
11929: my ($file) = @_;
11930: foreach my $configline (@$file) {
11931: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11932: chomp($configline);
11933: if ($configline =~ /^\^/) {
11934: if ($configline =~ /^\^([\w.\-]+)/) {
11935: $LC_dns_serv{$1} = 1;
11936: }
11937: next;
11938: }
1.1074 raeburn 11939: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11940: $name=~s/\s//g;
11941: if ($id && $domain && $role && $name) {
11942: $hostname{$id}=$name;
1.888 albertel 11943: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11944: $hostdom{$id}=$domain;
11945: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11946: if (defined($protocol)) {
11947: if ($protocol eq 'https') {
11948: $protocol{$id} = $protocol;
11949: } else {
11950: $protocol{$id} = 'http';
11951: }
1.968 raeburn 11952: } else {
1.969 raeburn 11953: $protocol{$id} = 'http';
1.968 raeburn 11954: }
1.1074 raeburn 11955: if (defined($intdom)) {
11956: $internetdom{$id} = $intdom;
11957: }
1.852 albertel 11958: }
11959: }
11960: }
1.864 albertel 11961:
11962: sub reset_hosts_info {
1.897 albertel 11963: &purge_remembered();
1.864 albertel 11964: &reset_domain_info();
11965: &reset_hosts_ip_info();
1.892 albertel 11966: undef(%name_to_host);
1.864 albertel 11967: undef(%hostname);
11968: undef(%hostdom);
11969: undef(%libserv);
11970: undef($loaded);
11971: }
1.1 albertel 11972:
1.852 albertel 11973: sub load_hosts_tab {
1.869 albertel 11974: my ($ignore_cache) = @_;
11975: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11976: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11977: my @config = <$config>;
11978: &parse_hosts_tab(\@config);
11979: close($config);
11980: $loaded=1;
1.1 albertel 11981: }
1.852 albertel 11982:
1.838 albertel 11983: sub hostname {
1.852 albertel 11984: &load_hosts_tab() if (!$loaded);
11985:
1.838 albertel 11986: my ($lonid) = @_;
11987: return $hostname{$lonid};
11988: }
1.845 albertel 11989:
1.838 albertel 11990: sub all_hostnames {
1.852 albertel 11991: &load_hosts_tab() if (!$loaded);
11992:
1.838 albertel 11993: return %hostname;
11994: }
1.845 albertel 11995:
1.888 albertel 11996: sub all_names {
11997: &load_hosts_tab() if (!$loaded);
11998:
11999: return %name_to_host;
12000: }
12001:
1.974 raeburn 12002: sub all_host_domain {
12003: &load_hosts_tab() if (!$loaded);
12004: return %hostdom;
12005: }
12006:
1.845 albertel 12007: sub is_library {
1.852 albertel 12008: &load_hosts_tab() if (!$loaded);
12009:
1.845 albertel 12010: return exists($libserv{$_[0]});
12011: }
12012:
12013: sub all_library {
1.852 albertel 12014: &load_hosts_tab() if (!$loaded);
12015:
1.845 albertel 12016: return %libserv;
12017: }
12018:
1.1062 droeschl 12019: sub unique_library {
12020: #2x reverse removes all hostnames that appear more than once
12021: my %unique = reverse &all_library();
12022: return reverse %unique;
12023: }
12024:
1.841 albertel 12025: sub get_servers {
1.852 albertel 12026: &load_hosts_tab() if (!$loaded);
12027:
1.841 albertel 12028: my ($domain,$type) = @_;
12029: my %possible_hosts = ($type eq 'library') ? %libserv
12030: : %hostname;
12031: my %result;
1.842 albertel 12032: if (ref($domain) eq 'ARRAY') {
12033: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12034: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12035: $result{$host} = $hostname;
12036: }
12037: }
12038: } else {
12039: while ( my ($host,$hostname) = each(%possible_hosts)) {
12040: if ($hostdom{$host} eq $domain) {
12041: $result{$host} = $hostname;
12042: }
1.841 albertel 12043: }
12044: }
12045: return %result;
12046: }
1.845 albertel 12047:
1.1062 droeschl 12048: sub get_unique_servers {
12049: my %unique = reverse &get_servers(@_);
12050: return reverse %unique;
12051: }
12052:
1.844 albertel 12053: sub host_domain {
1.852 albertel 12054: &load_hosts_tab() if (!$loaded);
12055:
1.844 albertel 12056: my ($lonid) = @_;
12057: return $hostdom{$lonid};
12058: }
12059:
1.841 albertel 12060: sub all_domains {
1.852 albertel 12061: &load_hosts_tab() if (!$loaded);
12062:
1.841 albertel 12063: my %seen;
12064: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12065: return @uniq;
12066: }
1.1074 raeburn 12067:
12068: sub internet_dom {
12069: &load_hosts_tab() if (!$loaded);
12070:
12071: my ($lonid) = @_;
12072: return $internetdom{$lonid};
12073: }
1.1107 raeburn 12074:
12075: sub is_LC_dns {
12076: &load_hosts_tab() if (!$loaded);
12077:
12078: my ($hostname) = @_;
12079: return exists($LC_dns_serv{$hostname});
12080: }
12081:
1.1 albertel 12082: }
12083:
1.847 albertel 12084: {
12085: my %iphost;
1.856 albertel 12086: my %name_to_ip;
12087: my %lonid_to_ip;
1.869 albertel 12088:
1.847 albertel 12089: sub get_hosts_from_ip {
12090: my ($ip) = @_;
12091: my %iphosts = &get_iphost();
12092: if (ref($iphosts{$ip})) {
12093: return @{$iphosts{$ip}};
12094: }
12095: return;
1.839 albertel 12096: }
1.864 albertel 12097:
12098: sub reset_hosts_ip_info {
12099: undef(%iphost);
12100: undef(%name_to_ip);
12101: undef(%lonid_to_ip);
12102: }
1.856 albertel 12103:
12104: sub get_host_ip {
12105: my ($lonid) = @_;
12106: if (exists($lonid_to_ip{$lonid})) {
12107: return $lonid_to_ip{$lonid};
12108: }
12109: my $name=&hostname($lonid);
12110: my $ip = gethostbyname($name);
12111: return if (!$ip || length($ip) ne 4);
12112: $ip=inet_ntoa($ip);
12113: $name_to_ip{$name} = $ip;
12114: $lonid_to_ip{$lonid} = $ip;
12115: return $ip;
12116: }
1.847 albertel 12117:
12118: sub get_iphost {
1.869 albertel 12119: my ($ignore_cache) = @_;
1.894 albertel 12120:
1.869 albertel 12121: if (!$ignore_cache) {
12122: if (%iphost) {
12123: return %iphost;
12124: }
12125: my ($ip_info,$cached)=
12126: &Apache::lonnet::is_cached_new('iphost','iphost');
12127: if ($cached) {
12128: %iphost = %{$ip_info->[0]};
12129: %name_to_ip = %{$ip_info->[1]};
12130: %lonid_to_ip = %{$ip_info->[2]};
12131: return %iphost;
12132: }
12133: }
1.894 albertel 12134:
12135: # get yesterday's info for fallback
12136: my %old_name_to_ip;
12137: my ($ip_info,$cached)=
12138: &Apache::lonnet::is_cached_new('iphost','iphost');
12139: if ($cached) {
12140: %old_name_to_ip = %{$ip_info->[1]};
12141: }
12142:
1.888 albertel 12143: my %name_to_host = &all_names();
12144: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12145: my $ip;
12146: if (!exists($name_to_ip{$name})) {
12147: $ip = gethostbyname($name);
12148: if (!$ip || length($ip) ne 4) {
1.894 albertel 12149: if (defined($old_name_to_ip{$name})) {
12150: $ip = $old_name_to_ip{$name};
12151: &logthis("Can't find $name defaulting to old $ip");
12152: } else {
12153: &logthis("Name $name no IP found");
12154: next;
12155: }
12156: } else {
12157: $ip=inet_ntoa($ip);
1.847 albertel 12158: }
12159: $name_to_ip{$name} = $ip;
12160: } else {
12161: $ip = $name_to_ip{$name};
1.653 albertel 12162: }
1.888 albertel 12163: foreach my $id (@{ $name_to_host{$name} }) {
12164: $lonid_to_ip{$id} = $ip;
12165: }
12166: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12167: }
1.1172.2.23 raeburn 12168: &do_cache_new('iphost','iphost',
12169: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12170: 48*60*60);
1.869 albertel 12171:
1.847 albertel 12172: return %iphost;
1.598 albertel 12173: }
12174:
1.992 raeburn 12175: #
12176: # Given a DNS returns the loncapa host name for that DNS
12177: #
12178: sub host_from_dns {
12179: my ($dns) = @_;
12180: my @hosts;
12181: my $ip;
12182:
1.993 raeburn 12183: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12184: $ip = $name_to_ip{$dns};
12185: }
12186: if (!$ip) {
12187: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12188: if (length($ip) == 4) {
12189: $ip = &IO::Socket::inet_ntoa($ip);
12190: }
12191: }
12192: if ($ip) {
12193: @hosts = get_hosts_from_ip($ip);
12194: return $hosts[0];
12195: }
12196: return undef;
1.986 foxr 12197: }
1.992 raeburn 12198:
1.1074 raeburn 12199: sub get_internet_names {
12200: my ($lonid) = @_;
12201: return if ($lonid eq '');
12202: my ($idnref,$cached)=
12203: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12204: if ($cached) {
12205: return $idnref;
12206: }
12207: my $ip = &get_host_ip($lonid);
12208: my @hosts = &get_hosts_from_ip($ip);
12209: my %iphost = &get_iphost();
12210: my (@idns,%seen);
12211: foreach my $id (@hosts) {
12212: my $dom = &host_domain($id);
12213: my $prim_id = &domain($dom,'primary');
12214: my $prim_ip = &get_host_ip($prim_id);
12215: next if ($seen{$prim_ip});
12216: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12217: foreach my $id (@{$iphost{$prim_ip}}) {
12218: my $intdom = &internet_dom($id);
12219: unless (grep(/^\Q$intdom\E$/,@idns)) {
12220: push(@idns,$intdom);
12221: }
12222: }
12223: }
12224: $seen{$prim_ip} = 1;
12225: }
1.1172.2.23 raeburn 12226: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12227: }
12228:
1.986 foxr 12229: }
12230:
1.1079 raeburn 12231: sub all_loncaparevs {
1.1172.2.39 raeburn 12232: 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 12233: }
12234:
1.1172.2.27 raeburn 12235: # ------------------------------------------------------- Read loncaparev table
12236: {
12237: sub load_loncaparevs {
12238: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12239: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12240: while (my $configline=<$config>) {
12241: chomp($configline);
12242: my ($hostid,$loncaparev)=split(/:/,$configline);
12243: $loncaparevs{$hostid}=$loncaparev;
12244: }
12245: close($config);
12246: }
12247: }
12248: }
12249: }
12250:
12251: # ----------------------------------------------------- Read serverhostID table
12252: {
12253: sub load_serverhomeIDs {
12254: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12255: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12256: while (my $configline=<$config>) {
12257: chomp($configline);
12258: my ($name,$id)=split(/:/,$configline);
12259: $serverhomeIDs{$name}=$id;
12260: }
12261: close($config);
12262: }
12263: }
12264: }
12265: }
12266:
12267:
1.862 albertel 12268: BEGIN {
12269:
12270: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12271: unless ($readit) {
12272: {
12273: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12274: %perlvar = (%perlvar,%{$configvars});
12275: }
12276:
12277:
1.1 albertel 12278: # ------------------------------------------------------ Read spare server file
12279: {
1.448 albertel 12280: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12281:
12282: while (my $configline=<$config>) {
12283: chomp($configline);
1.284 matthew 12284: if ($configline) {
1.784 albertel 12285: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12286: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12287: push(@{ $spareid{$type} }, $host);
1.1 albertel 12288: }
12289: }
1.448 albertel 12290: close($config);
1.1 albertel 12291: }
1.11 www 12292: # ------------------------------------------------------------ Read permissions
12293: {
1.448 albertel 12294: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12295:
12296: while (my $configline=<$config>) {
1.448 albertel 12297: chomp($configline);
12298: if ($configline) {
12299: my ($role,$perm)=split(/ /,$configline);
12300: if ($perm ne '') { $pr{$role}=$perm; }
12301: }
1.11 www 12302: }
1.448 albertel 12303: close($config);
1.11 www 12304: }
12305:
12306: # -------------------------------------------- Read plain texts for permissions
12307: {
1.448 albertel 12308: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12309:
12310: while (my $configline=<$config>) {
1.448 albertel 12311: chomp($configline);
12312: if ($configline) {
1.742 raeburn 12313: my ($short,@plain)=split(/:/,$configline);
12314: %{$prp{$short}} = ();
12315: if (@plain > 0) {
12316: $prp{$short}{'std'} = $plain[0];
12317: for (my $i=1; $i<@plain; $i++) {
12318: $prp{$short}{'alt'.$i} = $plain[$i];
12319: }
12320: }
1.448 albertel 12321: }
1.135 www 12322: }
1.448 albertel 12323: close($config);
1.135 www 12324: }
12325:
12326: # ---------------------------------------------------------- Read package table
12327: {
1.448 albertel 12328: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12329:
12330: while (my $configline=<$config>) {
1.483 albertel 12331: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12332: chomp($configline);
12333: my ($short,$plain)=split(/:/,$configline);
12334: my ($pack,$name)=split(/\&/,$short);
12335: if ($plain ne '') {
12336: $packagetab{$pack.'&'.$name.'&name'}=$name;
12337: $packagetab{$short}=$plain;
12338: }
1.11 www 12339: }
1.448 albertel 12340: close($config);
1.329 matthew 12341: }
12342:
1.1172.2.27 raeburn 12343: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 12344:
1.1172.2.27 raeburn 12345: &load_loncaparevs();
12346:
12347: # ------------------------------------------------------- Read serverhostID table
12348:
12349: &load_serverhomeIDs();
1.1074 raeburn 12350:
1.1172.2.27 raeburn 12351: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12352: {
12353: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12354: if (-e $file) {
12355: my $parser = HTML::LCParser->new($file);
12356: while (my $token = $parser->get_token()) {
12357: if ($token->[0] eq 'S') {
12358: my $item = $token->[1];
12359: my $name = $token->[2]{'name'};
12360: my $value = $token->[2]{'value'};
12361: if ($item ne '' && $name ne '' && $value ne '') {
12362: my $release = $parser->get_text();
12363: $release =~ s/(^\s*|\s*$ )//gx;
12364: $needsrelease{$item.':'.$name.':'.$value} = $release;
12365: }
12366: }
12367: }
12368: }
1.1073 raeburn 12369: }
12370:
1.1138 raeburn 12371: # ---------------------------------------------------------- Read managers table
12372: {
12373: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12374: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12375: while (my $configline=<$config>) {
12376: chomp($configline);
12377: next if ($configline =~ /^\#/);
12378: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12379: $managerstab{$configline} = 1;
12380: }
12381: }
12382: close($config);
12383: }
12384: }
12385: }
12386:
1.329 matthew 12387: # ------------- set up temporary directory
12388: {
1.1117 foxr 12389: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12390:
1.11 www 12391: }
12392:
1.794 albertel 12393: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12394: 'compress_threshold'=> 20_000,
12395: });
1.185 www 12396:
1.281 www 12397: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12398: $dumpcount=0;
1.958 www 12399: $locknum=0;
1.22 www 12400:
1.163 harris41 12401: &logtouch();
1.672 albertel 12402: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12403: $readit=1;
1.564 albertel 12404: {
12405: use integer;
12406: my $test=(2**32)+1;
1.568 albertel 12407: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12408: &logthis(" Detected 64bit platform ($_64bit)");
12409: }
1.195 www 12410: }
1.1 albertel 12411: }
1.179 www 12412:
1.1 albertel 12413: 1;
1.191 harris41 12414: __END__
12415:
1.243 albertel 12416: =pod
12417:
1.191 harris41 12418: =head1 NAME
12419:
1.243 albertel 12420: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12421:
12422: =head1 SYNOPSIS
12423:
1.243 albertel 12424: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12425:
12426: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12427:
1.243 albertel 12428: Common parameters:
12429:
12430: =over 4
12431:
12432: =item *
12433:
12434: $uname : an internal username (if $cname expecting a course Id specifically)
12435:
12436: =item *
12437:
12438: $udom : a domain (if $cdom expecting a course's domain specifically)
12439:
12440: =item *
12441:
12442: $symb : a resource instance identifier
12443:
12444: =item *
12445:
12446: $namespace : the name of a .db file that contains the data needed or
12447: being set.
12448:
12449: =back
12450:
1.394 bowersj2 12451: =head1 OVERVIEW
1.191 harris41 12452:
1.394 bowersj2 12453: lonnet provides subroutines which interact with the
12454: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12455: about classes, users, and resources.
1.243 albertel 12456:
12457: For many of these objects you can also use this to store data about
12458: them or modify them in various ways.
1.191 harris41 12459:
1.394 bowersj2 12460: =head2 Symbs
1.191 harris41 12461:
1.394 bowersj2 12462: To identify a specific instance of a resource, LON-CAPA uses symbols
12463: or "symbs"X<symb>. These identifiers are built from the URL of the
12464: map, the resource number of the resource in the map, and the URL of
12465: the resource itself. The latter is somewhat redundant, but might help
12466: if maps change.
12467:
12468: An example is
12469:
12470: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12471:
12472: The respective map entry is
12473:
12474: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12475: title="Problem 2">
12476: </resource>
12477:
12478: Symbs are used by the random number generator, as well as to store and
12479: restore data specific to a certain instance of for example a problem.
12480:
12481: =head2 Storing And Retrieving Data
12482:
12483: X<store()>X<cstore()>X<restore()>Three of the most important functions
12484: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12485: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12486: is is the non-critical message twin of cstore. These functions are for
12487: handlers to store a perl hash to a user's permanent data space in an
12488: easy manner, and to retrieve it again on another call. It is expected
12489: that a handler would use this once at the beginning to retrieve data,
12490: and then again once at the end to send only the new data back.
12491:
12492: The data is stored in the user's data directory on the user's
12493: homeserver under the ID of the course.
12494:
12495: The hash that is returned by restore will have all of the previous
12496: value for all of the elements of the hash.
12497:
12498: Example:
12499:
12500: #creating a hash
12501: my %hash;
12502: $hash{'foo'}='bar';
12503:
12504: #storing it
12505: &Apache::lonnet::cstore(\%hash);
12506:
12507: #changing a value
12508: $hash{'foo'}='notbar';
12509:
12510: #adding a new value
12511: $hash{'bar'}='foo';
12512: &Apache::lonnet::cstore(\%hash);
12513:
12514: #retrieving the hash
12515: my %history=&Apache::lonnet::restore();
12516:
12517: #print the hash
12518: foreach my $key (sort(keys(%history))) {
12519: print("\%history{$key} = $history{$key}");
12520: }
12521:
12522: Will print out:
1.191 harris41 12523:
1.394 bowersj2 12524: %history{1:foo} = bar
12525: %history{1:keys} = foo:timestamp
12526: %history{1:timestamp} = 990455579
12527: %history{2:bar} = foo
12528: %history{2:foo} = notbar
12529: %history{2:keys} = foo:bar:timestamp
12530: %history{2:timestamp} = 990455580
12531: %history{bar} = foo
12532: %history{foo} = notbar
12533: %history{timestamp} = 990455580
12534: %history{version} = 2
12535:
12536: Note that the special hash entries C<keys>, C<version> and
12537: C<timestamp> were added to the hash. C<version> will be equal to the
12538: total number of versions of the data that have been stored. The
12539: C<timestamp> attribute will be the UNIX time the hash was
12540: stored. C<keys> is available in every historical section to list which
12541: keys were added or changed at a specific historical revision of a
12542: hash.
12543:
12544: B<Warning>: do not store the hash that restore returns directly. This
12545: will cause a mess since it will restore the historical keys as if the
12546: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12547:
1.394 bowersj2 12548: Calling convention:
1.191 harris41 12549:
1.1172.2.27 raeburn 12550: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12551: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12552:
1.394 bowersj2 12553: For more detailed information, see lonnet specific documentation.
1.191 harris41 12554:
1.394 bowersj2 12555: =head1 RETURN MESSAGES
1.191 harris41 12556:
1.394 bowersj2 12557: =over 4
1.191 harris41 12558:
1.394 bowersj2 12559: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12560:
1.394 bowersj2 12561: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12562: when the connection is brought back up
1.191 harris41 12563:
1.394 bowersj2 12564: =item * B<con_failed>: unable to contact remote host and unable to save message
12565: for later delivery
1.191 harris41 12566:
1.967 bisitz 12567: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12568:
1.394 bowersj2 12569: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12570: that was requested
1.191 harris41 12571:
1.243 albertel 12572: =back
1.191 harris41 12573:
1.243 albertel 12574: =head1 PUBLIC SUBROUTINES
1.191 harris41 12575:
1.243 albertel 12576: =head2 Session Environment Functions
1.191 harris41 12577:
1.243 albertel 12578: =over 4
1.191 harris41 12579:
1.394 bowersj2 12580: =item *
12581: X<appenv()>
1.949 raeburn 12582: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12583: the user envirnoment file, and will be restored for each access this
1.620 albertel 12584: user makes during this session, also modifies the %env for the current
1.949 raeburn 12585: process. Optional rolesarrayref - if defined contains a reference to an array
12586: of roles which are exempt from the restriction on modifying user.role entries
12587: in the user's environment.db and in %env.
1.191 harris41 12588:
12589: =item *
1.394 bowersj2 12590: X<delenv()>
1.987 raeburn 12591: B<delenv($delthis,$regexp)>: removes all items from the session
12592: environment file that begin with $delthis. If the
12593: optional second arg - $regexp - is true, $delthis is treated as a
12594: regular expression, otherwise \Q$delthis\E is used.
12595: The values are also deleted from the current processes %env.
1.191 harris41 12596:
1.795 albertel 12597: =item * get_env_multiple($name)
12598:
12599: gets $name from the %env hash, it seemlessly handles the cases where multiple
12600: values may be defined and end up as an array ref.
12601:
12602: returns an array of values
12603:
1.243 albertel 12604: =back
12605:
12606: =head2 User Information
1.191 harris41 12607:
1.243 albertel 12608: =over 4
1.191 harris41 12609:
12610: =item *
1.394 bowersj2 12611: X<queryauthenticate()>
12612: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12613: authentication scheme
12614:
12615: =item *
1.394 bowersj2 12616: X<authenticate()>
1.1073 raeburn 12617: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12618: authenticate user from domain's lib servers (first use the current
12619: one). C<$upass> should be the users password.
1.1073 raeburn 12620: $checkdefauth is optional (value is 1 if a check should be made to
12621: authenticate user using default authentication method, and allow
12622: account creation if username does not have account in the domain).
12623: $clientcancheckhost is optional (value is 1 if checking whether the
12624: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12625:
12626: =item *
1.394 bowersj2 12627: X<homeserver()>
12628: B<homeserver($uname,$udom)>: find the server which has
12629: the user's directory and files (there must be only one), this caches
12630: the answer, and also caches if there is a borken connection.
1.191 harris41 12631:
12632: =item *
1.394 bowersj2 12633: X<idget()>
12634: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12635: (IDs are a unique resource in a domain, there must be only 1 ID per
12636: username, and only 1 username per ID in a specific domain) (returns
12637: hash: id=>name,id=>name)
1.191 harris41 12638:
12639: =item *
1.394 bowersj2 12640: X<idrget()>
12641: B<idrget($udom,@unames)>: find the IDs behind a list of
12642: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12643:
12644: =item *
1.394 bowersj2 12645: X<idput()>
12646: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12647:
12648: =item *
1.394 bowersj2 12649: X<rolesinit()>
1.1169 droeschl 12650: B<rolesinit($udom,$username)>: get user privileges.
12651: returns user role, first access and timer interval hashes
1.243 albertel 12652:
12653: =item *
1.1171 droeschl 12654: X<privileged()>
12655: B<privileged($username,$domain)>: returns a true if user has a
12656: privileged and active role (i.e. su or dc), false otherwise.
12657:
12658: =item *
1.551 albertel 12659: X<getsection()>
12660: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12661: course $cname, return section name/number or '' for "not in course"
12662: and '-1' for "no section"
12663:
12664: =item *
1.394 bowersj2 12665: X<userenvironment()>
12666: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12667: passed in @what from the requested user's environment, returns a hash
12668:
1.858 raeburn 12669: =item *
12670: X<userlog_query()>
1.859 albertel 12671: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12672: activity.log file. %filters defines filters applied when parsing the
12673: log file. These can be start or end timestamps, or the type of action
12674: - log to look for Login or Logout events, check for Checkin or
12675: Checkout, role for role selection. The response is in the form
12676: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12677: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12678:
1.243 albertel 12679: =back
12680:
12681: =head2 User Roles
12682:
12683: =over 4
12684:
12685: =item *
12686:
1.810 raeburn 12687: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12688: F: full access
12689: U,I,K: authentication modes (cxx only)
12690: '': forbidden
12691: 1: user needs to choose course
12692: 2: browse allowed
1.766 albertel 12693: A: passphrase authentication needed
1.243 albertel 12694:
12695: =item *
12696:
1.1172.2.13 raeburn 12697: constructaccess($url,$setpriv) : check for access to construction space URL
12698:
12699: See if the owner domain and name in the URL match those in the
12700: expected environment. If so, return three element list
12701: ($ownername,$ownerdomain,$ownerhome).
12702:
12703: Otherwise return the null string.
12704:
12705: If second argument 'setpriv' is true, it assigns the privileges,
12706: and returns the same three element list, unless the owner has
12707: blocked "ad hoc" Domain Coordinator access to the Author Space,
12708: in which case the null string is returned.
12709:
12710: =item *
12711:
1.243 albertel 12712: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12713: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12714: and course level
12715:
12716: =item *
12717:
1.988 raeburn 12718: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12719: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12720: $type is Course (default) or Community.
1.988 raeburn 12721: If $forcedefault evaluates to true, text returned will be default
12722: text for $type. Otherwise, if this is a course, the text returned
12723: will be a custom name for the role (if defined in the course's
12724: environment). If no custom name is defined the default is returned.
12725:
1.832 raeburn 12726: =item *
12727:
1.1172.2.23 raeburn 12728: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12729: All arguments are optional. Returns a hash of a roles, either for
12730: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12731: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12732: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12733: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12734: For each key, value is set to colon-separated start and end times for
12735: the role. If no username and domain are specified, will default to
1.934 raeburn 12736: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12737: of role statuses (active, future or previous), roles
12738: (e.g., cc,in, st etc.) and domains of the roles which can be used
12739: to restrict the list of roles reported. If no array ref is
12740: provided for types, will default to return only active roles.
1.834 albertel 12741:
1.1172.2.13 raeburn 12742: =item *
12743:
12744: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12745: user: $uname:$udom has a role in the course: $cdom_$cnum.
12746:
12747: Additional optional arguments are: $type (if role checking is to be restricted
12748: to certain user status types -- previous (expired roles), active (currently
12749: available roles) or future (roles available in the future), and
12750: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 12751: have active Domain Coordinator role in course's domain or in additional
12752: domains (specified in 'Domains to check for privileged users' in course
12753: environment -- set via: Course Settings -> Classlists and staff listing).
12754:
12755: =item *
12756:
12757: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12758: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12759: $possdomains and $possroles are optional array refs -- to domains to check and
12760: roles to check. If $possdomains is not specified, a dump will be done of the
12761: users' roles.db to check for a dc or su role in any domain. This can be
12762: time consuming if &privileged is called repeatedly (e.g., when displaying a
12763: classlist), so in such cases, supplying a $possdomains array is preferred, as
12764: this then allows &privileged_by_domain() to be used, which caches the identity
12765: of privileged users, eliminating the need for repeated calls to &dump().
12766:
12767: =item *
12768:
12769: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12770: where the outer hash keys are domains specified in the $possdomains array ref,
12771: next inner hash keys are privileged roles specified in the $roles array ref,
12772: and the innermost hash contains key = value pairs for username:domain = end:start
12773: for active or future "privileged" users with that role in that domain. To avoid
12774: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12775: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 12776:
1.243 albertel 12777: =back
12778:
12779: =head2 User Modification
12780:
12781: =over 4
12782:
12783: =item *
12784:
1.957 raeburn 12785: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12786: user for the level given by URL. Optional start and end dates (leave empty
12787: string or zero for "no date")
1.191 harris41 12788:
12789: =item *
12790:
1.243 albertel 12791: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12792: change a users, password, possible return values are: ok,
12793: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12794: refused
1.191 harris41 12795:
12796: =item *
12797:
1.243 albertel 12798: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12799:
12800: =item *
12801:
1.1058 raeburn 12802: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12803: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12804:
12805: will update user information (firstname,middlename,lastname,generation,
12806: permanentemail), and if forceid is true, student/employee ID also.
12807: A user's institutional affiliation(s) can also be updated.
12808: User information fields will not be overwritten with empty entries
12809: unless the field is included in the $candelete array reference.
12810: This array is included when a single user is modified via "Manage Users",
12811: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12812:
12813: =item *
12814:
1.286 matthew 12815: modifystudent
12816:
1.957 raeburn 12817: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 12818: The course id is resolved based on the current user's environment.
12819: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12820: associated with a course.
12821:
1.297 matthew 12822: This call is essentially a wrapper for lonnet::modifyuser and
12823: lonnet::modify_student_enrollment
1.286 matthew 12824:
12825: Inputs:
12826:
12827: =over 4
12828:
1.957 raeburn 12829: =item B<$udom> Student's loncapa domain
1.286 matthew 12830:
1.957 raeburn 12831: =item B<$uname> Student's loncapa login name
1.286 matthew 12832:
1.964 bisitz 12833: =item B<$uid> Student/Employee ID
1.286 matthew 12834:
1.957 raeburn 12835: =item B<$umode> Student's authentication mode
1.286 matthew 12836:
1.957 raeburn 12837: =item B<$upass> Student's password
1.286 matthew 12838:
1.957 raeburn 12839: =item B<$first> Student's first name
1.286 matthew 12840:
1.957 raeburn 12841: =item B<$middle> Student's middle name
1.286 matthew 12842:
1.957 raeburn 12843: =item B<$last> Student's last name
1.286 matthew 12844:
1.957 raeburn 12845: =item B<$gene> Student's generation
1.286 matthew 12846:
1.957 raeburn 12847: =item B<$usec> Student's section in course
1.286 matthew 12848:
12849: =item B<$end> Unix time of the roles expiration
12850:
12851: =item B<$start> Unix time of the roles start date
12852:
12853: =item B<$forceid> If defined, allow $uid to be changed
12854:
12855: =item B<$desiredhome> server to use as home server for student
12856:
1.957 raeburn 12857: =item B<$email> Student's permanent e-mail address
12858:
12859: =item B<$type> Type of enrollment (auto or manual)
12860:
1.963 raeburn 12861: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12862:
12863: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12864:
1.963 raeburn 12865: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12866:
1.963 raeburn 12867: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12868:
1.1172.2.19 raeburn 12869: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12870:
12871: =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 12872:
1.286 matthew 12873: =back
1.297 matthew 12874:
12875: =item *
12876:
12877: modify_student_enrollment
12878:
1.1172.2.31 raeburn 12879: Change a student's enrollment status in a class. The environment variable
1.297 matthew 12880: 'role.request.course' must be defined for this function to proceed.
12881:
12882: Inputs:
12883:
12884: =over 4
12885:
1.1172.2.31 raeburn 12886: =item $udom, student's domain
1.297 matthew 12887:
1.1172.2.31 raeburn 12888: =item $uname, student's name
1.297 matthew 12889:
1.1172.2.31 raeburn 12890: =item $uid, student's user id
1.297 matthew 12891:
1.1172.2.31 raeburn 12892: =item $first, student's first name
1.297 matthew 12893:
12894: =item $middle
12895:
12896: =item $last
12897:
12898: =item $gene
12899:
12900: =item $usec
12901:
12902: =item $end
12903:
12904: =item $start
12905:
1.957 raeburn 12906: =item $type
12907:
12908: =item $locktype
12909:
12910: =item $cid
12911:
12912: =item $selfenroll
12913:
12914: =item $context
12915:
1.1172.2.19 raeburn 12916: =item $credits, number of credits student will earn from this class
12917:
1.297 matthew 12918: =back
12919:
1.191 harris41 12920:
12921: =item *
12922:
1.243 albertel 12923: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12924: custom role; give a custom role to a user for the level given by URL. Specify
12925: name and domain of role author, and role name
1.191 harris41 12926:
12927: =item *
12928:
1.243 albertel 12929: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12930:
12931: =item *
12932:
1.243 albertel 12933: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12934:
12935: =back
12936:
12937: =head2 Course Infomation
12938:
12939: =over 4
1.191 harris41 12940:
12941: =item *
12942:
1.1118 foxr 12943: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12944: specified course id, including all environment settings for the
12945: course, the description of the course will be in the hash under the
12946: key 'description'
1.191 harris41 12947:
1.1118 foxr 12948: $options is an optional parameter that if supplied is a hash reference that controls
12949: what how this function works. It has the following key/values:
12950:
12951: =over 4
12952:
12953: =item freshen_cache
12954:
12955: If defined, and the environment cache for the course is valid, it is
12956: returned in the returned hash.
12957:
12958: =item one_time
12959:
12960: If defined, the last cache time is set to _now_
12961:
12962: =item user
12963:
12964: If defined, the supplied username is used instead of the current user.
12965:
12966:
12967: =back
12968:
1.191 harris41 12969: =item *
12970:
1.624 albertel 12971: resdata($name,$domain,$type,@which) : request for current parameter
12972: setting for a specific $type, where $type is either 'course' or 'user',
12973: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 12974: answers for 10 minutes.
1.243 albertel 12975:
1.877 foxr 12976: =item *
12977:
12978: get_courseresdata($courseid, $domain) : dump the entire course resource
12979: data base, returning a hash that is keyed by the resource name and has
12980: values that are the resource value. I believe that the timestamps and
12981: versions are also returned.
12982:
1.1172.2.31 raeburn 12983: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12984: supplemental content area. This routine caches the number of files for
12985: 10 minutes.
12986:
1.243 albertel 12987: =back
12988:
12989: =head2 Course Modification
12990:
12991: =over 4
1.191 harris41 12992:
12993: =item *
12994:
1.243 albertel 12995: writecoursepref($courseid,%prefs) : write preferences (environment
12996: database) for a course
1.191 harris41 12997:
12998: =item *
12999:
1.1011 raeburn 13000: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13001:
13002: =item *
13003:
1.1038 raeburn 13004: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13005:
1.1167 droeschl 13006: =item *
13007:
13008: is_course($courseid), is_course($cdom, $cnum)
13009:
13010: Accepts either a combined $courseid (in the form of domain_courseid) or the
13011: two component version $cdom, $cnum. It checks if the specified course exists.
13012:
13013: Returns:
13014: undef if the course doesn't exist, otherwise
13015: in scalar context the combined courseid.
13016: in list context the two components of the course identifier, domain and
13017: courseid.
13018:
1.243 albertel 13019: =back
13020:
13021: =head2 Resource Subroutines
13022:
13023: =over 4
1.191 harris41 13024:
13025: =item *
13026:
1.243 albertel 13027: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13028:
13029: =item *
13030:
1.243 albertel 13031: repcopy($filename) : subscribes to the requested file, and attempts to
13032: replicate from the owning library server, Might return
1.607 raeburn 13033: 'unavailable', 'not_found', 'forbidden', 'ok', or
13034: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13035: resource. Expects the local filesystem pathname
13036: (/home/httpd/html/res/....)
13037:
13038: =back
13039:
13040: =head2 Resource Information
13041:
13042: =over 4
1.191 harris41 13043:
13044: =item *
13045:
1.1172.2.28 raeburn 13046: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13047: and returns the value of a variety of different possible values,
13048: $varname should be a request string, and the other parameters can be
13049: used to specify who and what one is asking about. Ordinarily, $cid
13050: does not need to be specified, as it is retrived from
13051: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13052: within lonuserstate::loadmap() when initializing a course, before
13053: $env{'request.course.id'} has been set, so it needs to be provided
13054: in that one case.
1.243 albertel 13055:
13056: Possible values for $varname are environment.lastname (or other item
13057: from the envirnment hash), user.name (or someother aspect about the
13058: user), resource.0.maxtries (or some other part and parameter of a
13059: resource)
1.204 albertel 13060:
13061: =item *
13062:
1.243 albertel 13063: directcondval($number) : get current value of a condition; reads from a state
13064: string
1.204 albertel 13065:
13066: =item *
13067:
1.243 albertel 13068: condval($condidx) : value of condition index based on state
1.204 albertel 13069:
13070: =item *
13071:
1.243 albertel 13072: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13073: resource's metadata, $what should be either a specific key, or either
13074: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13075: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13076:
13077: this function automatically caches all requests
1.191 harris41 13078:
13079: =item *
13080:
1.243 albertel 13081: metadata_query($query,$custom,$customshow) : make a metadata query against the
13082: network of library servers; returns file handle of where SQL and regex results
13083: will be stored for query
1.191 harris41 13084:
13085: =item *
13086:
1.243 albertel 13087: symbread($filename) : return symbolic list entry (filename argument optional);
13088: returns the data handle
1.191 harris41 13089:
13090: =item *
13091:
1.1172.2.17 raeburn 13092: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 13093: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13094: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 13095: on failure, user must be in a course, as it assumes the existence of
13096: the course initial hash, and uses $env('request.course.id'}. The third
13097: arg is an optional reference to a scalar. If this arg is passed in the
13098: call to symbverify, it will be set to 1 if the symb has been set to be
13099: encrypted; otherwise it will be null.
1.243 albertel 13100:
1.191 harris41 13101: =item *
13102:
1.243 albertel 13103: symbclean($symb) : removes versions numbers from a symb, returns the
13104: cleaned symb
1.191 harris41 13105:
13106: =item *
13107:
1.243 albertel 13108: is_on_map($uri) : checks if the $uri is somewhere on the current
13109: course map, user must be in a course for it to work.
1.191 harris41 13110:
13111: =item *
13112:
1.243 albertel 13113: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13114:
13115: =item *
13116:
1.243 albertel 13117: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13118: a random seed, all arguments are optional, if they aren't sent it uses the
13119: environment to derive them. Note: if symb isn't sent and it can't get one
13120: from &symbread it will use the current time as its return value
1.191 harris41 13121:
13122: =item *
13123:
1.243 albertel 13124: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13125: unfakeable, receipt
1.191 harris41 13126:
13127: =item *
13128:
1.620 albertel 13129: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13130:
13131: =item *
13132:
1.243 albertel 13133: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13134:
13135: =item *
13136:
1.243 albertel 13137: 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 13138:
13139: =item *
13140:
1.243 albertel 13141: 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 13142:
13143: =item *
13144:
1.243 albertel 13145: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13146:
13147: =item *
13148:
1.243 albertel 13149: devalidate($symb) : devalidate temporary spreadsheet calculations,
13150: forcing spreadsheet to reevaluate the resource scores next time.
13151:
1.1172.2.13 raeburn 13152: =item *
13153:
13154: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13155: when viewing in course context.
13156:
13157: input: six args -- filename (decluttered), course number, course domain,
13158: url, symb (if registered) and group (if this is a
13159: group item -- e.g., bulletin board, group page etc.).
13160:
13161: output: array of five scalars --
13162: $cfile -- url for file editing if editable on current server
13163: $home -- homeserver of resource (i.e., for author if published,
13164: or course if uploaded.).
13165: $switchserver -- 1 if server switch will be needed.
13166: $forceedit -- 1 if icon/link should be to go to edit mode
13167: $forceview -- 1 if icon/link should be to go to view mode
13168:
13169: =item *
13170:
13171: is_course_upload($file,$cnum,$cdom)
13172:
13173: Used in course context to determine if current file was uploaded to
13174: the course (i.e., would be found in /userfiles/docs on the course's
13175: homeserver.
13176:
13177: input: 3 args -- filename (decluttered), course number and course domain.
13178: output: boolean -- 1 if file was uploaded.
13179:
1.243 albertel 13180: =back
13181:
13182: =head2 Storing/Retreiving Data
13183:
13184: =over 4
1.191 harris41 13185:
13186: =item *
13187:
1.243 albertel 13188: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13189: for this url; hashref needs to be given and should be a \%hashname; the
13190: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13191: be derived from the env
1.191 harris41 13192:
13193: =item *
13194:
1.243 albertel 13195: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13196: uses critical subroutine
1.191 harris41 13197:
13198: =item *
13199:
1.243 albertel 13200: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13201: all args are optional
1.191 harris41 13202:
13203: =item *
13204:
1.717 albertel 13205: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13206: dumps the complete (or key matching regexp) namespace into a hash
13207: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13208: normally &store()ed into
13209:
13210: $range should be either an integer '100' (give me the first 100
13211: matching records)
13212: or be two integers sperated by a - with no spaces
13213: '30-50' (give me the 30th through the 50th matching
13214: records)
13215:
13216:
13217: =item *
13218:
13219: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13220: replaces a &store() version of data with a replacement set of data
13221: for a particular resource in a namespace passed in the $storehash hash
13222: reference
13223:
13224: =item *
13225:
1.243 albertel 13226: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13227: works very similar to store/cstore, but all data is stored in a
13228: temporary location and can be reset using tmpreset, $storehash should
13229: be a hash reference, returns nothing on success
1.191 harris41 13230:
13231: =item *
13232:
1.243 albertel 13233: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13234: similar to restore, but all data is stored in a temporary location and
13235: can be reset using tmpreset. Returns a hash of values on success,
13236: error string otherwise.
1.191 harris41 13237:
13238: =item *
13239:
1.243 albertel 13240: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13241: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13242:
13243: =item *
13244:
1.243 albertel 13245: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13246: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13247:
13248: =item *
13249:
1.243 albertel 13250: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13251: namesp ($udom and $uname are optional)
1.191 harris41 13252:
13253: =item *
13254:
1.702 albertel 13255: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13256: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13257: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13258:
1.702 albertel 13259: $range should be either an integer '100' (give me the first 100
13260: matching records)
13261: or be two integers sperated by a - with no spaces
13262: '30-50' (give me the 30th through the 50th matching
13263: records)
1.449 matthew 13264: =item *
13265:
13266: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13267: $store can be a scalar, an array reference, or if the amount to be
13268: incremented is > 1, a hash reference.
13269:
13270: ($udom and $uname are optional)
1.191 harris41 13271:
13272: =item *
13273:
1.243 albertel 13274: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13275: ($udom and $uname are optional)
1.191 harris41 13276:
13277: =item *
13278:
1.243 albertel 13279: cput($namespace,$storehash,$udom,$uname) : critical put
13280: ($udom and $uname are optional)
1.191 harris41 13281:
13282: =item *
13283:
1.748 albertel 13284: newput($namespace,$storehash,$udom,$uname) :
13285:
13286: Attempts to store the items in the $storehash, but only if they don't
13287: currently exist, if this succeeds you can be certain that you have
13288: successfully created a new key value pair in the $namespace db.
13289:
13290:
13291: Args:
13292: $namespace: name of database to store values to
13293: $storehash: hashref to store to the db
13294: $udom: (optional) domain of user containing the db
13295: $uname: (optional) name of user caontaining the db
13296:
13297: Returns:
13298: 'ok' -> succeeded in storing all keys of $storehash
13299: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13300: least <key> already existed in the db (other
13301: requested keys may also already exist)
1.967 bisitz 13302: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13303: 'con_lost' -> unable to contact request server
13304: 'refused' -> action was not allowed by remote machine
13305:
13306:
13307: =item *
13308:
1.243 albertel 13309: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13310: reference filled in from namesp (encrypts the return communication)
13311: ($udom and $uname are optional)
1.191 harris41 13312:
13313: =item *
13314:
1.243 albertel 13315: log($udom,$name,$home,$message) : write to permanent log for user; use
13316: critical subroutine
13317:
1.806 raeburn 13318: =item *
13319:
1.860 raeburn 13320: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13321: array reference filled in from namespace found in domain level on either
13322: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13323:
13324: =item *
13325:
1.860 raeburn 13326: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13327: domain level either on specified domain server ($uhome) or primary domain
13328: server ($udom and $uhome are optional)
1.806 raeburn 13329:
1.943 raeburn 13330: =item *
13331:
1.1172.2.35 raeburn 13332: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13333: for: authentication, language, quotas, timezone, date locale, and portal URL in
13334: the target domain.
13335:
13336: May also include additional key => value pairs for the following groups:
13337:
13338: =over
13339:
13340: =item
13341: disk quotas (MB allocated by default to portfolios and authoring spaces).
13342:
13343: =over
13344:
13345: =item defaultquota, authorquota
13346:
13347: =back
13348:
13349: =item
13350: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13351: portfolio for users).
13352:
13353: =over
13354:
13355: =item
13356: aboutme, blog, webdav, portfolio
13357:
13358: =back
13359:
13360: =item
13361: requestcourses: ability to request courses, and how requests are processed.
13362:
13363: =over
13364:
13365: =item
1.1172.2.37 raeburn 13366: official, unofficial, community, textbook
1.1172.2.35 raeburn 13367:
13368: =back
13369:
13370: =item
13371: inststatus: types of institutional affiliation, and order in which they are displayed.
13372:
13373: =over
13374:
13375: =item
13376: inststatustypes, inststatusorder
13377:
13378: =back
13379:
13380: =item
13381: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13382: for course's uploaded content.
13383:
13384: =over
13385:
13386: =item
1.1172.2.37 raeburn 13387: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, communityquota, textbookquota
1.1172.2.35 raeburn 13388:
13389: =back
13390:
13391: =item
13392: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13393: on your servers.
13394:
13395: =over
13396:
13397: =item
13398: remotesessions, hostedsessions
13399:
13400: =back
13401:
13402: =back
13403:
13404: In cases where a domain coordinator has never used the "Set Domain Configuration"
13405: utility to create a configuration.db file on a domain's primary library server
13406: only the following domain defaults: auth_def, auth_arg_def, lang_def
13407: -- corresponding values are authentication type (internal, krb4, krb5,
13408: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13409: will be available. Values are retrieved from cache (if current), unless the
13410: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13411: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13412:
13413: Typical usage:
1.943 raeburn 13414:
1.1172.2.35 raeburn 13415: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13416:
1.243 albertel 13417: =back
13418:
13419: =head2 Network Status Functions
13420:
13421: =over 4
1.191 harris41 13422:
13423: =item *
13424:
1.1137 raeburn 13425: dirlist() : return directory list based on URI (first arg).
13426:
13427: Inputs: 1 required, 5 optional.
13428:
13429: =over
13430:
13431: =item
13432: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13433:
13434: =item
13435: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13436:
13437: =item
13438: $username - username of user/course to be listed. Extracted from $uri if absent.
13439:
13440: =item
13441: $getpropath - boolean: 1 if prepend path using &propath().
13442:
13443: =item
13444: $getuserdir - boolean: 1 if prepend path for "userfiles".
13445:
13446: =item
13447: $alternateRoot - path to prepend in place of path from $uri.
13448:
13449: =back
13450:
13451: Returns: Array of up to two items.
13452:
13453: =over
13454:
13455: a reference to an array of files/subdirectories
13456:
13457: =over
13458:
13459: Each element in the array of files/subdirectories is a & separated list of
13460: item name and the result of running stat on the item. If dirlist was requested
13461: for a file instead of a directory, the item name will be ''. For a directory
13462: listing, if the item is a metadata file, the element will end &N&M
13463: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13464: default copyright set (1).
13465:
13466: =back
13467:
13468: a scalar containing error condition (if encountered).
13469:
13470: =over
13471:
13472: =item
13473: no_host (no homeserver identified for $username:$domain).
13474:
13475: =item
13476: no_such_host (server contacted for listing not identified as valid host).
13477:
13478: =item
13479: con_lost (connection to remote server failed).
13480:
13481: =item
13482: refused (invalid $username:$domain received on lond side).
13483:
13484: =item
13485: no_such_dir (directory at specified path on lond side does not exist).
13486:
13487: =item
13488: empty (directory at specified path on lond side is empty).
13489:
13490: =over
13491:
13492: This is currently not encountered because the &ls3, &ls2,
13493: &ls (_handler) routines on the lond side do not filter out
13494: . and .. from a directory listing.
13495:
13496: =back
13497:
13498: =back
13499:
13500: =back
1.191 harris41 13501:
13502: =item *
13503:
1.243 albertel 13504: spareserver() : find server with least workload from spare.tab
13505:
1.986 foxr 13506:
13507: =item *
13508:
13509: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13510: if there is no corresponding loncapa host.
13511:
1.243 albertel 13512: =back
13513:
1.986 foxr 13514:
1.243 albertel 13515: =head2 Apache Request
13516:
13517: =over 4
1.191 harris41 13518:
13519: =item *
13520:
1.243 albertel 13521: ssi($url,%hash) : server side include, does a complete request cycle on url to
13522: localhost, posts hash
13523:
13524: =back
13525:
13526: =head2 Data to String to Data
13527:
13528: =over 4
1.191 harris41 13529:
13530: =item *
13531:
1.243 albertel 13532: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13533: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13534:
13535: =item *
13536:
1.243 albertel 13537: hashref2str($hashref) : convert a hashref into a string complete with
13538: escaping and '=' and '&' separators, supports elements that are
13539: arrayrefs and hashrefs
1.191 harris41 13540:
13541: =item *
13542:
1.243 albertel 13543: arrayref2str($arrayref) : convert an arrayref into a string complete
13544: with escaping and '&' separators, supports elements that are arrayrefs
13545: and hashrefs
1.191 harris41 13546:
13547: =item *
13548:
1.243 albertel 13549: str2hash($string) : convert string to hash using unescaping and
13550: splitting on '=' and '&', supports elements that are arrayrefs and
13551: hashrefs
1.191 harris41 13552:
13553: =item *
13554:
1.243 albertel 13555: str2array($string) : convert string to hash using unescaping and
13556: splitting on '&', supports elements that are arrayrefs and hashrefs
13557:
13558: =back
13559:
13560: =head2 Logging Routines
13561:
13562:
13563: These routines allow one to make log messages in the lonnet.log and
13564: lonnet.perm logfiles.
1.191 harris41 13565:
1.1119 foxr 13566: =over 4
13567:
1.191 harris41 13568: =item *
13569:
1.243 albertel 13570: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13571:
13572: =item *
13573:
1.243 albertel 13574: logthis() : append message to the normal lonnet.log file, it gets
13575: preiodically rolled over and deleted.
1.191 harris41 13576:
13577: =item *
13578:
1.243 albertel 13579: logperm() : append a permanent message to lonnet.perm.log, this log
13580: file never gets deleted by any automated portion of the system, only
13581: messages of critical importance should go in here.
13582:
1.1119 foxr 13583:
1.243 albertel 13584: =back
13585:
13586: =head2 General File Helper Routines
13587:
13588: =over 4
1.191 harris41 13589:
13590: =item *
13591:
1.481 raeburn 13592: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13593: (a) files in /uploaded
13594: (i) If a local copy of the file exists -
13595: compares modification date of local copy with last-modified date for
13596: definitive version stored on home server for course. If local copy is
13597: stale, requests a new version from the home server and stores it.
13598: If the original has been removed from the home server, then local copy
13599: is unlinked.
13600: (ii) If local copy does not exist -
13601: requests the file from the home server and stores it.
13602:
13603: If $caller is 'uploadrep':
13604: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13605: for request for files originally uploaded via DOCS.
13606: - returns 'ok' if fresh local copy now available, -1 otherwise.
13607:
13608: Otherwise:
13609: This indicates a call from the content generation phase of the request.
13610: - returns the entire contents of the file or -1.
13611:
13612: (b) files in /res
13613: - returns the entire contents of a file or -1;
13614: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13615:
1.712 albertel 13616:
13617: =item *
13618:
13619: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13620: reference
13621:
13622: returns either a stat() list of data about the file or an empty list
13623: if the file doesn't exist or couldn't find out about it (connection
13624: problems or user unknown)
13625:
1.191 harris41 13626: =item *
13627:
1.243 albertel 13628: filelocation($dir,$file) : returns file system location of a file
13629: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13630: directory that relative $file lookups are to looked in ($dir of /a/dir
13631: and a file of ../bob will become /a/bob)
1.191 harris41 13632:
13633: =item *
13634:
13635: hreflocation($dir,$file) : returns file system location or a URL; same as
13636: filelocation except for hrefs
13637:
13638: =item *
13639:
13640: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13641:
1.243 albertel 13642: =back
13643:
1.608 albertel 13644: =head2 Usererfile file routines (/uploaded*)
13645:
13646: =over 4
13647:
13648: =item *
13649:
13650: userfileupload(): main rotine for putting a file in a user or course's
13651: filespace, arguments are,
13652:
1.620 albertel 13653: formname - required - this is the name of the element in $env where the
1.608 albertel 13654: filename, and the contents of the file to create/modifed exist
1.620 albertel 13655: the filename is in $env{'form.'.$formname.'.filename'} and the
13656: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13657: context - if coursedoc, store the file in the course of the active role
13658: of the current user;
13659: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13660: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13661: subdir - required - subdirectory to put the file in under ../userfiles/
13662: if undefined, it will be placed in "unknown"
13663:
13664: (This routine calls clean_filename() to remove any dangerous
13665: characters from the filename, and then calls finuserfileupload() to
13666: complete the transaction)
13667:
13668: returns either the url of the uploaded file (/uploaded/....) if successful
13669: and /adm/notfound.html if unsuccessful
13670:
13671: =item *
13672:
13673: clean_filename(): routine for cleaing a filename up for storage in
13674: userfile space, argument is:
13675:
13676: filename - proposed filename
13677:
13678: returns: the new clean filename
13679:
13680: =item *
13681:
1.1090 raeburn 13682: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13683: userspace, probably shouldn't be called directly
13684:
13685: docuname: username or courseid of destination for the file
13686: docudom: domain of user/course of destination for the file
13687: formname: same as for userfileupload()
1.1090 raeburn 13688: fname: filename (including subdirectories) for the file
13689: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13690: allfiles: reference to hash used to store objects found by parser
13691: codebase: reference to hash used for codebases of java objects found by parser
13692: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13693: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13694: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13695: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13696: context: if 'overwrite', will move the uploaded file from its temporary location to
13697: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13698: mimetype: reference to scalar to accommodate mime type determined
13699: from File::MMagic if $parser = parse.
1.608 albertel 13700:
13701: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13702: and /adm/notfound.html if unsuccessful (or an error message if context
13703: was 'overwrite').
13704:
1.608 albertel 13705:
13706: =item *
13707:
13708: renameuserfile(): renames an existing userfile to a new name
13709:
13710: Args:
13711: docuname: username or courseid of destination for the file
13712: docudom: domain of user/course of destination for the file
13713: old: current file name (including any subdirs under userfiles)
13714: new: desired file name (including any subdirs under userfiles)
13715:
13716: =item *
13717:
13718: mkdiruserfile(): creates a directory is a userfiles dir
13719:
13720: Args:
13721: docuname: username or courseid of destination for the file
13722: docudom: domain of user/course of destination for the file
13723: dir: dir to create (including any subdirs under userfiles)
13724:
13725: =item *
13726:
13727: removeuserfile(): removes a file that exists in userfiles
13728:
13729: Args:
13730: docuname: username or courseid of destination for the file
13731: docudom: domain of user/course of destination for the file
13732: fname: filname to delete (including any subdirs under userfiles)
13733:
13734: =item *
13735:
13736: removeuploadedurl(): convience function for removeuserfile()
13737:
13738: Args:
13739: url: a full /uploaded/... url to delete
13740:
1.747 albertel 13741: =item *
13742:
13743: get_portfile_permissions():
13744: Args:
13745: domain: domain of user or course contain the portfolio files
13746: user: name of user or num of course contain the portfolio files
13747: Returns:
13748: hashref of a dump of the proper file_permissions.db
13749:
13750:
13751: =item *
13752:
13753: get_access_controls():
13754:
13755: Args:
13756: current_permissions: the hash ref returned from get_portfile_permissions()
13757: group: (optional) the group you want the files associated with
13758: file: (optional) the file you want access info on
13759:
13760: Returns:
1.749 raeburn 13761: a hash (keys are file names) of hashes containing
13762: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13763: values are XML containing access control settings (see below)
1.747 albertel 13764:
13765: Internal notes:
13766:
1.749 raeburn 13767: access controls are stored in file_permissions.db as key=value pairs.
13768: key -> path to file/file_name\0uniqueID:scope_end_start
13769: where scope -> public,guest,course,group,domains or users.
13770: end -> UNIX time for end of access (0 -> no end date)
13771: start -> UNIX time for start of access
13772:
13773: value -> XML description of access control
13774: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13775: <start></start>
13776: <end></end>
13777:
13778: <password></password> for scope type = guest
13779:
13780: <domain></domain> for scope type = course or group
13781: <number></number>
13782: <roles id="">
13783: <role></role>
13784: <access></access>
13785: <section></section>
13786: <group></group>
13787: </roles>
13788:
13789: <dom></dom> for scope type = domains
13790:
13791: <users> for scope type = users
13792: <user>
13793: <uname></uname>
13794: <udom></udom>
13795: </user>
13796: </users>
13797: </scope>
13798:
13799: Access data is also aggregated for each file in an additional key=value pair:
13800: key -> path to file/file_name\0accesscontrol
13801: value -> reference to hash
13802: hash contains key = value pairs
13803: where key = uniqueID:scope_end_start
13804: value = UNIX time record was last updated
13805:
13806: Used to improve speed of look-ups of access controls for each file.
13807:
13808: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13809:
1.1172.2.13 raeburn 13810: =item *
13811:
1.749 raeburn 13812: modify_access_controls():
13813:
13814: Modifies access controls for a portfolio file
13815: Args
13816: 1. file name
13817: 2. reference to hash of required changes,
13818: 3. domain
13819: 4. username
13820: where domain,username are the domain of the portfolio owner
13821: (either a user or a course)
13822:
13823: Returns:
13824: 1. result of additions or updates ('ok' or 'error', with error message).
13825: 2. result of deletions ('ok' or 'error', with error message).
13826: 3. reference to hash of any new or updated access controls.
13827: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13828: key = integer (inbound ID)
1.1172.2.13 raeburn 13829: value = uniqueID
13830:
13831: =item *
13832:
13833: get_timebased_id():
13834:
13835: Attempts to get a unique timestamp-based suffix for use with items added to a
13836: course via the Course Editor (e.g., folders, composite pages,
13837: group bulletin boards).
13838:
13839: Args: (first three required; six others optional)
13840:
13841: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13842: docssequence, or name of group
13843:
13844: 2. keyid (alphanumeric): name of temporary locking key in hash,
13845: e.g., num, boardids
13846:
13847: 3. namespace: name of gdbm file used to store suffixes already assigned;
13848: file will be named nohist_namespace.db
13849:
13850: 4. cdom: domain of course; default is current course domain from %env
13851:
13852: 5. cnum: course number; default is current course number from %env
13853:
13854: 6. idtype: set to concat if an additional digit is to be appended to the
13855: unix timestamp to form the suffix, if the plain timestamp is already
13856: in use. Default is to not do this, but simply increment the unix
13857: timestamp by 1 until a unique key is obtained.
13858:
13859: 7. who: holder of locking key; defaults to user:domain for user.
13860:
13861: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13862: retrying); default is 3.
13863:
13864: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13865:
13866: Returns:
13867:
13868: 1. suffix obtained (numeric)
13869:
13870: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13871:
13872: 3. error: contains (localized) error message if an error occurred.
13873:
1.747 albertel 13874:
1.608 albertel 13875: =back
13876:
1.243 albertel 13877: =head2 HTTP Helper Routines
13878:
13879: =over 4
13880:
1.191 harris41 13881: =item *
13882:
13883: escape() : unpack non-word characters into CGI-compatible hex codes
13884:
13885: =item *
13886:
13887: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13888:
1.243 albertel 13889: =back
13890:
13891: =head1 PRIVATE SUBROUTINES
13892:
13893: =head2 Underlying communication routines (Shouldn't call)
13894:
13895: =over 4
13896:
13897: =item *
13898:
13899: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13900:
13901: =item *
13902:
13903: reply() : uses subreply to send a message to remote machine, logs all failures
13904:
13905: =item *
13906:
13907: critical() : passes a critical message to another server; if cannot
13908: get through then place message in connection buffer directory and
13909: returns con_delayed, if incapable of saving message, returns
13910: con_failed
13911:
13912: =item *
13913:
13914: reconlonc() : tries to reconnect lonc client processes.
13915:
13916: =back
13917:
13918: =head2 Resource Access Logging
13919:
13920: =over 4
13921:
13922: =item *
13923:
13924: flushcourselogs() : flush (save) buffer logs and access logs
13925:
13926: =item *
13927:
13928: courselog($what) : save message for course in hash
13929:
13930: =item *
13931:
13932: courseacclog($what) : save message for course using &courselog(). Perform
13933: special processing for specific resource types (problems, exams, quizzes, etc).
13934:
1.191 harris41 13935: =item *
13936:
13937: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13938: as a PerlChildExitHandler
1.243 albertel 13939:
13940: =back
13941:
13942: =head2 Other
13943:
13944: =over 4
13945:
13946: =item *
13947:
13948: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 13949:
13950: =back
13951:
13952: =cut
1.877 foxr 13953:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>