Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.78
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.78! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.77 2016/08/07 23:33:50 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: if ($lonid) {
1.1172.2.72 raeburn 421: my $hostname = &hostname($lonid);
1.891 albertel 422: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
423: if ($hostname && -e $peerfile) {
424: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
425: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
426: Type => SOCK_STREAM,
427: Timeout => 10);
428: if ($client) {
429: print $client ("reset_retries\n");
430: my $answer=<$client>;
431: #reset just this one.
432: }
433: }
434: return;
435: }
436:
1.836 www 437: &logthis("Trying to reconnect lonc");
1.1 albertel 438: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 439: if (open(my $fh,"<$loncfile")) {
1.1 albertel 440: my $loncpid=<$fh>;
441: chomp($loncpid);
442: if (kill 0 => $loncpid) {
443: &logthis("lonc at pid $loncpid responding, sending USR1");
444: kill USR1 => $loncpid;
445: sleep 1;
1.836 www 446: } else {
1.12 www 447: &logthis(
1.672 albertel 448: "<font color=\"blue\">WARNING:".
1.12 www 449: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 450: }
451: } else {
1.836 www 452: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 453: }
454: }
455:
456: # ------------------------------------------------------ Critical communication
1.12 www 457:
1.1 albertel 458: sub critical {
459: my ($cmd,$server)=@_;
1.838 albertel 460: unless (&hostname($server)) {
1.672 albertel 461: &logthis("<font color=\"blue\">WARNING:".
1.89 www 462: " Critical message to unknown server ($server)</font>");
463: return 'no_such_host';
464: }
1.1 albertel 465: my $answer=reply($cmd,$server);
466: if ($answer eq 'con_lost') {
1.1172.2.72 raeburn 467: &reconlonc($server);
1.589 albertel 468: my $answer=reply($cmd,$server);
1.1 albertel 469: if ($answer eq 'con_lost') {
470: my $now=time;
471: my $middlename=$cmd;
1.5 www 472: $middlename=substr($middlename,0,16);
1.1 albertel 473: $middlename=~s/\W//g;
474: my $dfilename=
1.305 www 475: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
476: $dumpcount++;
1.1 albertel 477: {
1.448 albertel 478: my $dfh;
479: if (open($dfh,">$dfilename")) {
480: print $dfh "$cmd\n";
481: close($dfh);
482: }
1.1 albertel 483: }
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'} }) {
1.1172.2.62 raeburn 847: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
848: $try_server));
1.1123 raeburn 849: ($spare_server, $lowest_load) =
850: &compare_server_load($try_server, $spare_server, $lowest_load);
851: }
1.1083 raeburn 852: }
1.784 albertel 853:
1.1123 raeburn 854: my $found_server = ($spare_server ne '' && $lowest_load < 100);
855:
856: if (!$found_server) {
857: if (ref($spareshash->{'default'}) eq 'ARRAY') {
858: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62 raeburn 859: next unless (&spare_can_host($udom,$uint_dom,
860: $remotesessions,$try_server));
1.1123 raeburn 861: ($spare_server, $lowest_load) =
862: &compare_server_load($try_server, $spare_server, $lowest_load);
863: }
864: }
865: }
1.784 albertel 866: }
867:
868: if (!$want_server_name) {
1.968 raeburn 869: my $protocol = 'http';
870: if ($protocol{$spare_server} eq 'https') {
871: $protocol = $protocol{$spare_server};
872: }
1.1001 raeburn 873: if (defined($spare_server)) {
874: my $hostname = &hostname($spare_server);
1.1083 raeburn 875: if (defined($hostname)) {
1.1001 raeburn 876: $spare_server = $protocol.'://'.$hostname;
877: }
878: }
1.784 albertel 879: }
880: return $spare_server;
881: }
882:
883: sub compare_server_load {
1.1172.2.41 raeburn 884: my ($try_server, $spare_server, $lowest_load, $required) = @_;
885:
886: if ($required) {
887: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
888: my $remoterev = &get_server_loncaparev(undef,$try_server);
889: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
890: if (($major eq '' && $minor eq '') ||
891: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
892: return ($spare_server,$lowest_load);
893: }
894: }
1.784 albertel 895:
896: my $loadans = &reply('load', $try_server);
897: my $userloadans = &reply('userload',$try_server);
898:
899: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 900: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 901: }
902:
903: my $load;
904: if ($loadans =~ /\d/) {
905: if ($userloadans =~ /\d/) {
906: #both are numbers, pick the bigger one
907: $load = ($loadans > $userloadans) ? $loadans
908: : $userloadans;
1.411 albertel 909: } else {
1.784 albertel 910: $load = $loadans;
1.411 albertel 911: }
1.784 albertel 912: } else {
913: $load = $userloadans;
914: }
915:
916: if (($load =~ /\d/) && ($load < $lowest_load)) {
917: $spare_server = $try_server;
918: $lowest_load = $load;
1.370 albertel 919: }
1.784 albertel 920: return ($spare_server,$lowest_load);
1.202 matthew 921: }
1.914 albertel 922:
923: # --------------------------- ask offload servers if user already has a session
924: sub find_existing_session {
925: my ($udom,$uname) = @_;
1.1123 raeburn 926: my $spareshash = &this_host_spares($udom);
927: if (ref($spareshash) eq 'HASH') {
928: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
929: foreach my $try_server (@{ $spareshash->{'primary'} }) {
930: return $try_server if (&has_user_session($try_server, $udom, $uname));
931: }
932: }
933: if (ref($spareshash->{'default'}) eq 'ARRAY') {
934: foreach my $try_server (@{ $spareshash->{'default'} }) {
935: return $try_server if (&has_user_session($try_server, $udom, $uname));
936: }
937: }
1.914 albertel 938: }
939: return;
940: }
941:
942: # -------------------------------- ask if server already has a session for user
943: sub has_user_session {
944: my ($lonid,$udom,$uname) = @_;
945: my $result = &reply(join(':','userhassession',
946: map {&escape($_)} ($udom,$uname)),$lonid);
947: return 1 if ($result eq 'ok');
948:
949: return 0;
950: }
951:
1.1076 raeburn 952: # --------- determine least loaded server in a user's domain which allows login
953:
954: sub choose_server {
1.1172.2.47 raeburn 955: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 956: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 957: my %servers = &get_servers($udom);
1.1076 raeburn 958: my $lowest_load = 30000;
1.1172.2.47 raeburn 959: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
960: if ($skiploadbal) {
961: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
962: unless (defined($cached)) {
963: my $cachetime = 60*60*24;
964: my %domconfig =
965: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
966: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
967: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
968: $cachetime);
969: }
970: }
971: }
1.1076 raeburn 972: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 973: my $loginvia;
1.1172.2.47 raeburn 974: if ($skiploadbal) {
975: if (ref($balancers) eq 'HASH') {
976: next if (exists($balancers->{$lonhost}));
977: }
978: }
1.1115 raeburn 979: if ($checkloginvia) {
980: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 981: if ($loginvia) {
982: my ($server,$path) = split(/:/,$loginvia);
983: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 984: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 985: if ($login_host eq $server) {
986: $portal_path = $path;
1.1151 raeburn 987: $isredirect = 1;
1.1116 raeburn 988: }
989: } else {
990: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 991: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 992: if ($login_host eq $lonhost) {
993: $portal_path = '';
1.1151 raeburn 994: $isredirect = '';
1.1116 raeburn 995: }
996: }
997: } else {
1.1076 raeburn 998: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 999: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1000: }
1001: }
1002: if ($login_host ne '') {
1.1116 raeburn 1003: $hostname = &hostname($login_host);
1.1076 raeburn 1004: }
1.1151 raeburn 1005: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 1006: }
1007:
1.202 matthew 1008: # --------------------------------------------- Try to change a user's password
1009:
1010: sub changepass {
1.799 raeburn 1011: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1012: $currentpass = &escape($currentpass);
1013: $newpass = &escape($newpass);
1.1030 raeburn 1014: my $lonhost = $perlvar{'lonHostID'};
1015: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1016: $server);
1017: if (! $answer) {
1018: &logthis("No reply on password change request to $server ".
1019: "by $uname in domain $udom.");
1020: } elsif ($answer =~ "^ok") {
1021: &logthis("$uname in $udom successfully changed their password ".
1022: "on $server.");
1023: } elsif ($answer =~ "^pwchange_failure") {
1024: &logthis("$uname in $udom was unable to change their password ".
1025: "on $server. The action was blocked by either lcpasswd ".
1026: "or pwchange");
1027: } elsif ($answer =~ "^non_authorized") {
1028: &logthis("$uname in $udom did not get their password correct when ".
1029: "attempting to change it on $server.");
1030: } elsif ($answer =~ "^auth_mode_error") {
1031: &logthis("$uname in $udom attempted to change their password despite ".
1032: "not being locally or internally authenticated on $server.");
1033: } elsif ($answer =~ "^unknown_user") {
1034: &logthis("$uname in $udom attempted to change their password ".
1035: "on $server but were unable to because $server is not ".
1036: "their home server.");
1037: } elsif ($answer =~ "^refused") {
1038: &logthis("$server refused to change $uname in $udom password because ".
1039: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1040: } elsif ($answer =~ "invalid_client") {
1041: &logthis("$server refused to change $uname in $udom password because ".
1042: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1043: }
1044: return $answer;
1.1 albertel 1045: }
1046:
1.169 harris41 1047: # ----------------------- Try to determine user's current authentication scheme
1048:
1049: sub queryauthenticate {
1050: my ($uname,$udom)=@_;
1.456 albertel 1051: my $uhome=&homeserver($uname,$udom);
1052: if (!$uhome) {
1053: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1054: return 'no_host';
1055: }
1056: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1057: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1058: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1059: }
1.456 albertel 1060: return $answer;
1.169 harris41 1061: }
1062:
1.1 albertel 1063: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1064:
1.1 albertel 1065: sub authenticate {
1.1073 raeburn 1066: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1067: $upass=&escape($upass);
1068: $uname= &LONCAPA::clean_username($uname);
1.836 www 1069: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1070: my $newhome;
1.836 www 1071: if ((!$uhome) || ($uhome eq 'no_host')) {
1072: # Maybe the machine was offline and only re-appeared again recently?
1073: &reconlonc();
1074: # One more
1.952 raeburn 1075: $uhome=&homeserver($uname,$udom,1);
1076: if (($uhome eq 'no_host') && $checkdefauth) {
1077: if (defined(&domain($udom,'primary'))) {
1078: $newhome=&domain($udom,'primary');
1079: }
1080: if ($newhome ne '') {
1081: $uhome = $newhome;
1082: }
1083: }
1.836 www 1084: if ((!$uhome) || ($uhome eq 'no_host')) {
1085: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1086: return 'no_host';
1087: }
1.1 albertel 1088: }
1.1073 raeburn 1089: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1090: if ($answer eq 'authorized') {
1.952 raeburn 1091: if ($newhome) {
1092: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1093: return 'no_account_on_host';
1094: } else {
1095: &logthis("User $uname at $udom authorized by $uhome");
1096: return $uhome;
1097: }
1.471 albertel 1098: }
1099: if ($answer eq 'non_authorized') {
1100: &logthis("User $uname at $udom rejected by $uhome");
1101: return 'no_host';
1.9 www 1102: }
1.471 albertel 1103: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1104: return 'no_host';
1105: }
1106:
1.1073 raeburn 1107: sub can_host_session {
1.1074 raeburn 1108: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1109: my $canhost = 1;
1.1074 raeburn 1110: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1111: if (ref($remotesessions) eq 'HASH') {
1112: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1113: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1114: $canhost = 0;
1115: } else {
1116: $canhost = 1;
1117: }
1118: }
1119: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1120: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1121: $canhost = 1;
1122: } else {
1123: $canhost = 0;
1124: }
1125: }
1126: if ($canhost) {
1127: if ($remotesessions->{'version'} ne '') {
1128: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1129: if ($reqmajor ne '' && $reqminor ne '') {
1130: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1131: my $major = $1;
1132: my $minor = $2;
1133: if (($major < $reqmajor ) ||
1134: (($major == $reqmajor) && ($minor < $reqminor))) {
1135: $canhost = 0;
1136: }
1137: } else {
1138: $canhost = 0;
1139: }
1140: }
1141: }
1142: }
1143: }
1144: if ($canhost) {
1145: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1146: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1147: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1148: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1149: if (($uint_dom ne '') &&
1150: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1151: $canhost = 0;
1152: } else {
1153: $canhost = 1;
1154: }
1155: }
1156: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1157: if (($uint_dom ne '') &&
1158: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1159: $canhost = 1;
1160: } else {
1161: $canhost = 0;
1162: }
1163: }
1164: }
1165: }
1166: return $canhost;
1167: }
1168:
1.1083 raeburn 1169: sub spare_can_host {
1170: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1171: my $canhost=1;
1.1172.2.62 raeburn 1172: my $try_server_hostname = &hostname($try_server);
1173: my $serverhomeID = &get_server_homeID($try_server_hostname);
1174: my $serverhomedom = &host_domain($serverhomeID);
1175: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1176: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1177: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1178: $canhost = 0;
1179: }
1180: }
1181: if (($canhost) && ($uint_dom)) {
1182: my @intdoms;
1183: my $internet_names = &get_internet_names($try_server);
1184: if (ref($internet_names) eq 'ARRAY') {
1185: @intdoms = @{$internet_names};
1186: }
1187: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1188: my $remoterev = &get_server_loncaparev(undef,$try_server);
1189: $canhost = &can_host_session($udom,$try_server,$remoterev,
1190: $remotesessions,
1191: $defdomdefaults{'hostedsessions'});
1192: }
1.1083 raeburn 1193: }
1194: return $canhost;
1195: }
1196:
1.1123 raeburn 1197: sub this_host_spares {
1198: my ($dom) = @_;
1.1126 raeburn 1199: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1200: my @hosts = ¤t_machine_ids();
1201: foreach my $lonhost (@hosts) {
1202: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1203: $dom_in_use = $dom;
1204: $lonhost_in_use = $lonhost;
1.1123 raeburn 1205: last;
1206: }
1207: }
1.1126 raeburn 1208: if ($dom_in_use ne '') {
1209: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1210: }
1211: if (ref($result) ne 'HASH') {
1212: $lonhost_in_use = $perlvar{'lonHostID'};
1213: $dom_in_use = &host_domain($lonhost_in_use);
1214: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1215: if (ref($result) ne 'HASH') {
1216: $result = \%spareid;
1217: }
1218: }
1219: return $result;
1220: }
1221:
1222: sub spares_for_offload {
1223: my ($dom_in_use,$lonhost_in_use) = @_;
1224: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1225: if (defined($cached)) {
1226: return $result;
1227: } else {
1.1126 raeburn 1228: my $cachetime = 60*60*24;
1229: my %domconfig =
1230: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1231: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1232: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1233: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1234: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1235: }
1236: }
1237: }
1238: }
1.1126 raeburn 1239: return;
1.1123 raeburn 1240: }
1241:
1.1129 raeburn 1242: sub get_lonbalancer_config {
1243: my ($servers) = @_;
1244: my ($currbalancer,$currtargets);
1245: if (ref($servers) eq 'HASH') {
1246: foreach my $server (keys(%{$servers})) {
1247: my %what = (
1248: spareid => 1,
1249: perlvar => 1,
1250: );
1251: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1252: if ($result eq 'ok') {
1253: if (ref($returnhash) eq 'HASH') {
1254: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1255: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1256: $currbalancer = $server;
1257: $currtargets = {};
1258: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1259: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1260: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1261: }
1262: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1263: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1264: }
1265: }
1266: last;
1267: }
1268: }
1269: }
1270: }
1271: }
1272: }
1273: return ($currbalancer,$currtargets);
1274: }
1275:
1276: sub check_loadbalancing {
1277: my ($uname,$udom) = @_;
1.1172.2.12 raeburn 1278: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1279: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1280: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1281: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1282: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1283: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1284: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1285: my $serverhomedom = &host_domain($lonhost);
1.1172.2.75 raeburn 1286: my $domneedscache;
1.1129 raeburn 1287: my $cachetime = 60*60*24;
1288:
1289: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1290: $dom_in_use = $udom;
1291: $homeintdom = 1;
1292: } else {
1293: $dom_in_use = $serverhomedom;
1294: }
1295: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1296: unless (defined($cached)) {
1297: my %domconfig =
1298: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1299: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1300: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75 raeburn 1301: } else {
1302: $domneedscache = $dom_in_use;
1.1129 raeburn 1303: }
1304: }
1305: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1306: ($is_balancer,$currtargets,$currrules) =
1307: &check_balancer_result($result,@hosts);
1.1129 raeburn 1308: if ($is_balancer) {
1309: if (ref($currrules) eq 'HASH') {
1310: if ($homeintdom) {
1311: if ($uname ne '') {
1312: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1313: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1314: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1315: $rule_in_effect = $currrules->{'_LC_author'};
1316: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1317: $rule_in_effect = $currrules->{'_LC_adv'}
1318: }
1319: }
1320: if ($rule_in_effect eq '') {
1321: my %userenv = &userenvironment($udom,$uname,'inststatus');
1322: if ($userenv{'inststatus'} ne '') {
1323: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1324: my ($othertitle,$usertypes,$types) =
1325: &Apache::loncommon::sorted_inst_types($udom);
1326: if (ref($types) eq 'ARRAY') {
1327: foreach my $type (@{$types}) {
1328: if (grep(/^\Q$type\E$/,@statuses)) {
1329: if (exists($currrules->{$type})) {
1330: $rule_in_effect = $currrules->{$type};
1331: }
1332: }
1333: }
1334: }
1335: } else {
1336: if (exists($currrules->{'default'})) {
1337: $rule_in_effect = $currrules->{'default'};
1338: }
1339: }
1340: }
1341: } else {
1342: if (exists($currrules->{'default'})) {
1343: $rule_in_effect = $currrules->{'default'};
1344: }
1345: }
1346: } else {
1347: if ($currrules->{'_LC_external'} ne '') {
1348: $rule_in_effect = $currrules->{'_LC_external'};
1349: }
1350: }
1351: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1352: $uname,$udom);
1353: }
1354: }
1355: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1356: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1357: unless (defined($cached)) {
1358: my %domconfig =
1359: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1360: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75 raeburn 1361: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1362: } else {
1363: $domneedscache = $serverhomedom;
1.1129 raeburn 1364: }
1365: }
1366: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1367: ($is_balancer,$currtargets,$currrules) =
1368: &check_balancer_result($result,@hosts);
1369: if ($is_balancer) {
1.1129 raeburn 1370: if (ref($currrules) eq 'HASH') {
1371: if ($currrules->{'_LC_internetdom'} ne '') {
1372: $rule_in_effect = $currrules->{'_LC_internetdom'};
1373: }
1374: }
1375: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1376: $uname,$udom);
1377: }
1378: } else {
1379: if ($perlvar{'lonBalancer'} eq 'yes') {
1380: $is_balancer = 1;
1381: $offloadto = &this_host_spares($dom_in_use);
1382: }
1.1172.2.75 raeburn 1383: unless (defined($cached)) {
1384: $domneedscache = $serverhomedom;
1385: }
1.1129 raeburn 1386: }
1387: } else {
1388: if ($perlvar{'lonBalancer'} eq 'yes') {
1389: $is_balancer = 1;
1390: $offloadto = &this_host_spares($dom_in_use);
1391: }
1.1172.2.75 raeburn 1392: unless (defined($cached)) {
1393: $domneedscache = $serverhomedom;
1394: }
1395: }
1396: if ($domneedscache) {
1397: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1398: }
1.1172.2.5 raeburn 1399: if ($is_balancer) {
1400: my $lowest_load = 30000;
1401: if (ref($offloadto) eq 'HASH') {
1402: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1403: foreach my $try_server (@{$offloadto->{'primary'}}) {
1404: ($otherserver,$lowest_load) =
1405: &compare_server_load($try_server,$otherserver,$lowest_load);
1406: }
1.1129 raeburn 1407: }
1.1172.2.5 raeburn 1408: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1409:
1.1172.2.5 raeburn 1410: if (!$found_server) {
1411: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1412: foreach my $try_server (@{$offloadto->{'default'}}) {
1413: ($otherserver,$lowest_load) =
1414: &compare_server_load($try_server,$otherserver,$lowest_load);
1415: }
1416: }
1417: }
1418: } elsif (ref($offloadto) eq 'ARRAY') {
1419: if (@{$offloadto} == 1) {
1420: $otherserver = $offloadto->[0];
1421: } elsif (@{$offloadto} > 1) {
1422: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1423: ($otherserver,$lowest_load) =
1424: &compare_server_load($try_server,$otherserver,$lowest_load);
1425: }
1426: }
1427: }
1.1172.2.5 raeburn 1428: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1429: $is_balancer = 0;
1430: if ($uname ne '' && $udom ne '') {
1431: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1432:
1433: &appenv({'user.loadbalexempt' => $lonhost,
1434: 'user.loadbalcheck.time' => time});
1435: }
1.1129 raeburn 1436: }
1437: }
1438: }
1439: return ($is_balancer,$otherserver);
1440: }
1441:
1.1172.2.12 raeburn 1442: sub check_balancer_result {
1443: my ($result,@hosts) = @_;
1444: my ($is_balancer,$currtargets,$currrules);
1445: if (ref($result) eq 'HASH') {
1446: if ($result->{'lonhost'} ne '') {
1447: my $currbalancer = $result->{'lonhost'};
1448: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1449: $is_balancer = 1;
1450: $currtargets = $result->{'targets'};
1451: $currrules = $result->{'rules'};
1452: }
1453: } else {
1454: foreach my $key (keys(%{$result})) {
1455: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1456: (ref($result->{$key}) eq 'HASH')) {
1457: $is_balancer = 1;
1458: $currrules = $result->{$key}{'rules'};
1459: $currtargets = $result->{$key}{'targets'};
1460: last;
1461: }
1462: }
1463: }
1464: }
1465: return ($is_balancer,$currtargets,$currrules);
1466: }
1467:
1.1129 raeburn 1468: sub get_loadbalancer_targets {
1469: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1470: my $offloadto;
1.1172.2.4 raeburn 1471: if ($rule_in_effect eq 'none') {
1472: return [$perlvar{'lonHostID'}];
1473: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1474: $offloadto = $currtargets;
1475: } else {
1476: if ($rule_in_effect eq 'homeserver') {
1477: my $homeserver = &homeserver($uname,$udom);
1478: if ($homeserver ne 'no_host') {
1479: $offloadto = [$homeserver];
1480: }
1481: } elsif ($rule_in_effect eq 'externalbalancer') {
1482: my %domconfig =
1483: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1484: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1485: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1486: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1487: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1488: }
1489: }
1490: } else {
1.1172.2.7 raeburn 1491: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1492: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1493: if (&hostname($remotebalancer) ne '') {
1494: $offloadto = [$remotebalancer];
1495: }
1496: }
1497: } elsif (&hostname($rule_in_effect) ne '') {
1498: $offloadto = [$rule_in_effect];
1499: }
1500: }
1501: return $offloadto;
1502: }
1503:
1.1127 raeburn 1504: sub internet_dom_servers {
1505: my ($dom) = @_;
1506: my (%uniqservers,%servers);
1507: my $primaryserver = &hostname(&domain($dom,'primary'));
1508: my @machinedoms = &machine_domains($primaryserver);
1509: foreach my $mdom (@machinedoms) {
1510: my %currservers = %servers;
1511: my %server = &get_servers($mdom);
1512: %servers = (%currservers,%server);
1513: }
1514: my %by_hostname;
1515: foreach my $id (keys(%servers)) {
1516: push(@{$by_hostname{$servers{$id}}},$id);
1517: }
1518: foreach my $hostname (sort(keys(%by_hostname))) {
1519: if (@{$by_hostname{$hostname}} > 1) {
1520: my $match = 0;
1521: foreach my $id (@{$by_hostname{$hostname}}) {
1522: if (&host_domain($id) eq $dom) {
1523: $uniqservers{$id} = $hostname;
1524: $match = 1;
1525: }
1526: }
1527: unless ($match) {
1528: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1529: }
1530: } else {
1531: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1532: }
1533: }
1534: return %uniqservers;
1535: }
1536:
1.1 albertel 1537: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1538:
1.599 albertel 1539: my %homecache;
1.1 albertel 1540: sub homeserver {
1.230 stredwic 1541: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1542: my $index="$uname:$udom";
1.426 albertel 1543:
1.599 albertel 1544: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1545:
1546: my %servers = &get_servers($udom,'library');
1547: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1548: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1549: exists($badServerCache{$tryserver}));
1.841 albertel 1550:
1551: my $answer=reply("home:$udom:$uname",$tryserver);
1552: if ($answer eq 'found') {
1553: delete($badServerCache{$tryserver});
1554: return $homecache{$index}=$tryserver;
1555: } elsif ($answer eq 'no_host') {
1556: $badServerCache{$tryserver}=1;
1557: }
1.1 albertel 1558: }
1559: return 'no_host';
1.70 www 1560: }
1561:
1562: # ------------------------------------- Find the usernames behind a list of IDs
1563:
1564: sub idget {
1565: my ($udom,@ids)=@_;
1566: my %returnhash=();
1567:
1.841 albertel 1568: my %servers = &get_servers($udom,'library');
1569: foreach my $tryserver (keys(%servers)) {
1.1172.2.73 raeburn 1570: my $idlist=join('&', map { &escape($_); } @ids);
1.841 albertel 1571: $idlist=~tr/A-Z/a-z/;
1572: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1573: my @answer=();
1574: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1575: @answer=split(/\&/,$reply);
1576: } ;
1577: my $i;
1578: for ($i=0;$i<=$#ids;$i++) {
1579: if ($answer[$i]) {
1.1172.2.73 raeburn 1580: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841 albertel 1581: }
1582: }
1583: }
1.70 www 1584: return %returnhash;
1585: }
1586:
1587: # ------------------------------------- Find the IDs behind a list of usernames
1588:
1589: sub idrget {
1590: my ($udom,@unames)=@_;
1591: my %returnhash=();
1.800 albertel 1592: foreach my $uname (@unames) {
1593: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1594: }
1.70 www 1595: return %returnhash;
1596: }
1597:
1598: # ------------------------------- Store away a list of names and associated IDs
1599:
1600: sub idput {
1601: my ($udom,%ids)=@_;
1602: my %servers=();
1.800 albertel 1603: foreach my $uname (keys(%ids)) {
1604: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1605: my $uhom=&homeserver($uname,$udom);
1.70 www 1606: if ($uhom ne 'no_host') {
1.800 albertel 1607: my $id=&escape($ids{$uname});
1.70 www 1608: $id=~tr/A-Z/a-z/;
1.800 albertel 1609: my $esc_unam=&escape($uname);
1.70 www 1610: if ($servers{$uhom}) {
1.800 albertel 1611: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1612: } else {
1.800 albertel 1613: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1614: }
1615: }
1.191 harris41 1616: }
1.800 albertel 1617: foreach my $server (keys(%servers)) {
1618: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1619: }
1.344 www 1620: }
1621:
1.1172.2.30 raeburn 1622: # ---------------------------------------- Delete unwanted IDs from ids.db file
1623:
1624: sub iddel {
1625: my ($udom,$idshashref,$uhome)=@_;
1626: my %result=();
1627: unless (ref($idshashref) eq 'HASH') {
1628: return %result;
1629: }
1630: my %servers=();
1631: while (my ($id,$uname) = each(%{$idshashref})) {
1632: my $uhom;
1633: if ($uhome) {
1634: $uhom = $uhome;
1635: } else {
1636: $uhom=&homeserver($uname,$udom);
1637: }
1638: if ($uhom ne 'no_host') {
1639: if ($servers{$uhom}) {
1640: $servers{$uhom}.='&'.&escape($id);
1641: } else {
1642: $servers{$uhom}=&escape($id);
1643: }
1644: }
1645: }
1646: foreach my $server (keys(%servers)) {
1647: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1648: }
1649: return %result;
1650: }
1651:
1.1023 raeburn 1652: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1653: sub dump_dom {
1.1165 droeschl 1654: my ($namespace, $udom, $regexp) = @_;
1655:
1656: $udom ||= $env{'user.domain'};
1657:
1658: return () unless $udom;
1659:
1660: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1661: }
1662:
1.1023 raeburn 1663: # ------------------------------------------ get items from domain db files
1.806 raeburn 1664:
1665: sub get_dom {
1.860 raeburn 1666: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57 raeburn 1667: return if ($udom eq 'public');
1.806 raeburn 1668: my $items='';
1669: foreach my $item (@$storearr) {
1670: $items.=&escape($item).'&';
1671: }
1672: $items=~s/\&$//;
1.860 raeburn 1673: if (!$udom) {
1674: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1675: return if ($udom eq 'public');
1.860 raeburn 1676: if (defined(&domain($udom,'primary'))) {
1677: $uhome=&domain($udom,'primary');
1678: } else {
1.874 albertel 1679: undef($uhome);
1.860 raeburn 1680: }
1681: } else {
1682: if (!$uhome) {
1683: if (defined(&domain($udom,'primary'))) {
1684: $uhome=&domain($udom,'primary');
1685: }
1686: }
1687: }
1688: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1689: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1690: my %returnhash;
1.875 albertel 1691: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1692: return %returnhash;
1693: }
1.806 raeburn 1694: my @pairs=split(/\&/,$rep);
1695: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1696: return @pairs;
1697: }
1698: my $i=0;
1699: foreach my $item (@$storearr) {
1700: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1701: $i++;
1702: }
1703: return %returnhash;
1704: } else {
1.880 banghart 1705: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1706: }
1707: }
1708:
1709: # -------------------------------------------- put items in domain db files
1710:
1711: sub put_dom {
1.860 raeburn 1712: my ($namespace,$storehash,$udom,$uhome)=@_;
1713: if (!$udom) {
1714: $udom=$env{'user.domain'};
1715: if (defined(&domain($udom,'primary'))) {
1716: $uhome=&domain($udom,'primary');
1717: } else {
1.874 albertel 1718: undef($uhome);
1.860 raeburn 1719: }
1720: } else {
1721: if (!$uhome) {
1722: if (defined(&domain($udom,'primary'))) {
1723: $uhome=&domain($udom,'primary');
1724: }
1725: }
1726: }
1727: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1728: my $items='';
1729: foreach my $item (keys(%$storehash)) {
1730: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1731: }
1732: $items=~s/\&$//;
1733: return &reply("putdom:$udom:$namespace:$items",$uhome);
1734: } else {
1.860 raeburn 1735: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1736: }
1737: }
1738:
1.1023 raeburn 1739: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1740: sub newput_dom {
1.1023 raeburn 1741: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1742: my $result;
1743: if (!$udom) {
1744: $udom=$env{'user.domain'};
1745: }
1.1023 raeburn 1746: if ($udom) {
1747: my $uname = &get_domainconfiguser($udom);
1748: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1749: }
1750: return $result;
1751: }
1752:
1.1023 raeburn 1753: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1754: sub del_dom {
1.1023 raeburn 1755: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1756: if (ref($storearr) eq 'ARRAY') {
1757: if (!$udom) {
1758: $udom=$env{'user.domain'};
1759: }
1.1023 raeburn 1760: if ($udom) {
1761: my $uname = &get_domainconfiguser($udom);
1762: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1763: }
1764: }
1765: }
1766:
1.1023 raeburn 1767: # ----------------------------------construct domainconfig user for a domain
1768: sub get_domainconfiguser {
1769: my ($udom) = @_;
1770: return $udom.'-domainconfig';
1771: }
1772:
1.837 raeburn 1773: sub retrieve_inst_usertypes {
1774: my ($udom) = @_;
1775: my (%returnhash,@order);
1.989 raeburn 1776: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1777: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1778: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 1779: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1780: } else {
1781: if (defined(&domain($udom,'primary'))) {
1782: my $uhome=&domain($udom,'primary');
1783: my $rep=&reply("inst_usertypes:$udom",$uhome);
1784: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 1785: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1786: return (\%returnhash,\@order);
1787: }
1788: my ($hashitems,$orderitems) = split(/:/,$rep);
1789: my @pairs=split(/\&/,$hashitems);
1790: foreach my $item (@pairs) {
1791: my ($key,$value)=split(/=/,$item,2);
1792: $key = &unescape($key);
1793: next if ($key =~ /^error: 2 /);
1794: $returnhash{$key}=&thaw_unescape($value);
1795: }
1796: my @esc_order = split(/\&/,$orderitems);
1797: foreach my $item (@esc_order) {
1798: push(@order,&unescape($item));
1799: }
1800: } else {
1.1172.2.44 raeburn 1801: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1802: }
1.1172.2.44 raeburn 1803: return (\%returnhash,\@order);
1.837 raeburn 1804: }
1805: }
1806:
1.868 raeburn 1807: sub is_domainimage {
1808: my ($url) = @_;
1.1172.2.74 raeburn 1809: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 1810: if (&domain($1) ne '') {
1811: return '1';
1812: }
1813: }
1814: return;
1815: }
1816:
1.899 raeburn 1817: sub inst_directory_query {
1818: my ($srch) = @_;
1819: my $udom = $srch->{'srchdomain'};
1820: my %results;
1821: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1822: my $outcome;
1.899 raeburn 1823: if ($homeserver ne '') {
1.904 albertel 1824: my $queryid=&reply("querysend:instdirsearch:".
1825: &escape($srch->{'srchby'}).':'.
1826: &escape($srch->{'srchterm'}).':'.
1827: &escape($srch->{'srchtype'}),$homeserver);
1828: my $host=&hostname($homeserver);
1829: if ($queryid !~/^\Q$host\E\_/) {
1830: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1831: return;
1832: }
1833: my $response = &get_query_reply($queryid);
1834: my $maxtries = 5;
1835: my $tries = 1;
1836: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1837: $response = &get_query_reply($queryid);
1838: $tries ++;
1839: }
1840:
1841: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1842: if ($response eq 'unavailable') {
1843: $outcome = $response;
1844: } else {
1845: $outcome = 'ok';
1846: my @matches = split(/\n/,$response);
1847: foreach my $match (@matches) {
1848: my ($key,$value) = split(/=/,$match);
1849: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1850: }
1.899 raeburn 1851: }
1852: }
1853: }
1.909 raeburn 1854: return ($outcome,%results);
1.899 raeburn 1855: }
1856:
1857: sub usersearch {
1858: my ($srch) = @_;
1859: my $dom = $srch->{'srchdomain'};
1860: my %results;
1861: my %libserv = &all_library();
1862: my $query = 'usersearch';
1863: foreach my $tryserver (keys(%libserv)) {
1864: if (&host_domain($tryserver) eq $dom) {
1865: my $host=&hostname($tryserver);
1866: my $queryid=
1.911 raeburn 1867: &reply("querysend:".&escape($query).':'.
1868: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1869: &escape($srch->{'srchtype'}).':'.
1870: &escape($srch->{'srchterm'}),$tryserver);
1871: if ($queryid !~/^\Q$host\E\_/) {
1872: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1873: next;
1.899 raeburn 1874: }
1875: my $reply = &get_query_reply($queryid);
1876: my $maxtries = 1;
1877: my $tries = 1;
1878: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1879: $reply = &get_query_reply($queryid);
1880: $tries ++;
1881: }
1882: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1883: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1884: } else {
1.911 raeburn 1885: my @matches;
1886: if ($reply =~ /\n/) {
1887: @matches = split(/\n/,$reply);
1888: } else {
1889: @matches = split(/\&/,$reply);
1890: }
1.899 raeburn 1891: foreach my $match (@matches) {
1892: my ($uname,$udom,%userhash);
1.911 raeburn 1893: foreach my $entry (split(/:/,$match)) {
1894: my ($key,$value) =
1895: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1896: $userhash{$key} = $value;
1897: if ($key eq 'username') {
1898: $uname = $value;
1899: } elsif ($key eq 'domain') {
1900: $udom = $value;
1.911 raeburn 1901: }
1.899 raeburn 1902: }
1903: $results{$uname.':'.$udom} = \%userhash;
1904: }
1905: }
1906: }
1907: }
1908: return %results;
1909: }
1910:
1.912 raeburn 1911: sub get_instuser {
1912: my ($udom,$uname,$id) = @_;
1913: my $homeserver = &domain($udom,'primary');
1914: my ($outcome,%results);
1915: if ($homeserver ne '') {
1916: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1917: &escape($id).':'.&escape($udom),$homeserver);
1918: my $host=&hostname($homeserver);
1919: if ($queryid !~/^\Q$host\E\_/) {
1920: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1921: return;
1922: }
1923: my $response = &get_query_reply($queryid);
1924: my $maxtries = 5;
1925: my $tries = 1;
1926: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1927: $response = &get_query_reply($queryid);
1928: $tries ++;
1929: }
1930: if (!&error($response) && $response ne 'refused') {
1931: if ($response eq 'unavailable') {
1932: $outcome = $response;
1933: } else {
1934: $outcome = 'ok';
1935: my @matches = split(/\n/,$response);
1936: foreach my $match (@matches) {
1937: my ($key,$value) = split(/=/,$match);
1938: $results{&unescape($key)} = &thaw_unescape($value);
1939: }
1940: }
1941: }
1942: }
1943: my %userinfo;
1944: if (ref($results{$uname}) eq 'HASH') {
1945: %userinfo = %{$results{$uname}};
1946: }
1947: return ($outcome,%userinfo);
1948: }
1949:
1.1172.2.69 raeburn 1950: sub get_multiple_instusers {
1951: my ($udom,$users,$caller) = @_;
1952: my ($outcome,$results);
1953: if (ref($users) eq 'HASH') {
1954: my $count = keys(%{$users});
1955: my $requested = &freeze_escape($users);
1956: my $homeserver = &domain($udom,'primary');
1957: if ($homeserver ne '') {
1958: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
1959: my $host=&hostname($homeserver);
1960: if ($queryid !~/^\Q$host\E\_/) {
1961: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
1962: ' for host: '.$homeserver.'in domain '.$udom);
1963: return ($outcome,$results);
1964: }
1965: my $response = &get_query_reply($queryid);
1966: my $maxtries = 5;
1967: if ($count > 100) {
1968: $maxtries = 1+int($count/20);
1969: }
1970: my $tries = 1;
1971: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
1972: $response = &get_query_reply($queryid);
1973: $tries ++;
1974: }
1975: if ($response eq '') {
1976: $results = {};
1977: foreach my $key (keys(%{$users})) {
1978: my ($uname,$id);
1979: if ($caller eq 'id') {
1980: $id = $key;
1981: } else {
1982: $uname = $key;
1983: }
1984: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1985: $outcome = $resp;
1986: if ($resp eq 'ok') {
1987: %{$results} = (%{$results}, %info);
1988: } else {
1989: last;
1990: }
1991: }
1992: } elsif(!&error($response) && ($response ne 'refused')) {
1993: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
1994: $outcome = $response;
1995: } else {
1996: ($outcome,my $userdata) = split(/=/,$response,2);
1997: if ($outcome eq 'ok') {
1998: $results = &thaw_unescape($userdata);
1999: }
2000: }
2001: }
2002: }
2003: }
2004: return ($outcome,$results);
2005: }
2006:
1.912 raeburn 2007: sub inst_rulecheck {
1.923 raeburn 2008: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2009: my %returnhash;
2010: if ($udom ne '') {
2011: if (ref($rules) eq 'ARRAY') {
2012: @{$rules} = map {&escape($_);} (@{$rules});
2013: my $rulestr = join(':',@{$rules});
2014: my $homeserver=&domain($udom,'primary');
2015: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2016: my $response;
2017: if ($item eq 'username') {
2018: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2019: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2020: $homeserver));
1.923 raeburn 2021: } elsif ($item eq 'id') {
2022: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2023: ':'.&escape($id).':'.$rulestr,
2024: $homeserver));
1.945 raeburn 2025: } elsif ($item eq 'selfcreate') {
2026: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2027: &escape($udom).':'.&escape($uname).
2028: ':'.$rulestr,$homeserver));
1.923 raeburn 2029: }
1.912 raeburn 2030: if ($response ne 'refused') {
2031: my @pairs=split(/\&/,$response);
2032: foreach my $item (@pairs) {
2033: my ($key,$value)=split(/=/,$item,2);
2034: $key = &unescape($key);
2035: next if ($key =~ /^error: 2 /);
2036: $returnhash{$key}=&thaw_unescape($value);
2037: }
2038: }
2039: }
2040: }
2041: }
2042: return %returnhash;
2043: }
2044:
2045: sub inst_userrules {
1.923 raeburn 2046: my ($udom,$check) = @_;
1.912 raeburn 2047: my (%ruleshash,@ruleorder);
2048: if ($udom ne '') {
2049: my $homeserver=&domain($udom,'primary');
2050: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2051: my $response;
2052: if ($check eq 'id') {
2053: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2054: $homeserver);
1.943 raeburn 2055: } elsif ($check eq 'email') {
2056: $response=&reply('instemailrules:'.&escape($udom),
2057: $homeserver);
1.923 raeburn 2058: } else {
2059: $response=&reply('instuserrules:'.&escape($udom),
2060: $homeserver);
2061: }
1.912 raeburn 2062: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2063: ($response ne 'unknown_cmd') &&
1.912 raeburn 2064: ($response ne 'no_such_host')) {
2065: my ($hashitems,$orderitems) = split(/:/,$response);
2066: my @pairs=split(/\&/,$hashitems);
2067: foreach my $item (@pairs) {
2068: my ($key,$value)=split(/=/,$item,2);
2069: $key = &unescape($key);
2070: next if ($key =~ /^error: 2 /);
2071: $ruleshash{$key}=&thaw_unescape($value);
2072: }
2073: my @esc_order = split(/\&/,$orderitems);
2074: foreach my $item (@esc_order) {
2075: push(@ruleorder,&unescape($item));
2076: }
2077: }
2078: }
2079: }
2080: return (\%ruleshash,\@ruleorder);
2081: }
2082:
1.976 raeburn 2083: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2084:
2085: sub get_domain_defaults {
1.1172.2.35 raeburn 2086: my ($domain,$ignore_cache) = @_;
2087: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2088: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2089: unless ($ignore_cache) {
2090: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2091: if (defined($cached)) {
2092: if (ref($result) eq 'HASH') {
2093: return %{$result};
2094: }
1.943 raeburn 2095: }
2096: }
2097: my %domdefaults;
2098: my %domconfig =
1.989 raeburn 2099: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2100: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2101: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2102: 'requestauthor','selfenrollment',
1.1172.2.76 raeburn 2103: 'coursecategories','autoenroll'],$domain);
1.1172.2.41 raeburn 2104: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2105: if (ref($domconfig{'defaults'}) eq 'HASH') {
2106: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2107: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2108: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2109: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2110: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2111: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2112: } else {
2113: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2114: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2115: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2116: }
1.976 raeburn 2117: if (ref($domconfig{'quotas'}) eq 'HASH') {
2118: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2119: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2120: } else {
2121: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2122: }
1.1172.2.6 raeburn 2123: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2124: foreach my $item (@usertools) {
2125: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2126: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2127: }
2128: }
1.1172.2.29 raeburn 2129: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2130: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2131: }
1.976 raeburn 2132: }
1.985 raeburn 2133: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2134: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2135: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2136: }
2137: }
1.1172.2.9 raeburn 2138: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2139: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2140: }
1.989 raeburn 2141: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2142: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2143: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2144: }
2145: }
1.1047 raeburn 2146: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2147: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2148: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2149: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2150: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2151: }
1.1172.2.41 raeburn 2152: foreach my $type (@coursetypes) {
2153: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2154: unless ($type eq 'community') {
2155: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2156: }
2157: }
2158: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2159: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2160: }
1.1172.2.60 raeburn 2161: if ($domdefaults{'postsubmit'} eq 'on') {
2162: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2163: $domdefaults{$type.'postsubtimeout'} =
2164: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2165: }
2166: }
1.1172.2.30 raeburn 2167: }
1.1172.2.67 raeburn 2168: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2169: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2170: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2171: if (@clonecodes) {
2172: $domdefaults{'canclone'} = join('+',@clonecodes);
2173: }
2174: }
2175: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2176: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2177: }
1.1047 raeburn 2178: }
1.1073 raeburn 2179: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2180: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2181: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2182: }
2183: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2184: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2185: }
1.1172.2.62 raeburn 2186: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2187: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2188: }
1.1073 raeburn 2189: }
1.1172.2.41 raeburn 2190: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2191: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2192: my @settings = ('types','registered','enroll_dates','access_dates','section',
2193: 'approval','limit');
2194: foreach my $type (@coursetypes) {
2195: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2196: my @mgrdc = ();
2197: foreach my $item (@settings) {
2198: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2199: push(@mgrdc,$item);
2200: }
2201: }
2202: if (@mgrdc) {
2203: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2204: }
2205: }
2206: }
2207: }
2208: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2209: foreach my $type (@coursetypes) {
2210: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2211: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2212: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2213: }
2214: }
2215: }
2216: }
2217: }
1.1172.2.46 raeburn 2218: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2219: $domdefaults{'catauth'} = 'std';
2220: $domdefaults{'catunauth'} = 'std';
2221: if ($domconfig{'coursecategories'}{'auth'}) {
2222: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2223: }
2224: if ($domconfig{'coursecategories'}{'unauth'}) {
2225: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2226: }
2227: }
1.1172.2.76 raeburn 2228: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2229: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2230: }
1.1172.2.23 raeburn 2231: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2232: return %domdefaults;
2233: }
2234:
1.344 www 2235: # --------------------------------------------------- Assign a key to a student
2236:
2237: sub assign_access_key {
1.364 www 2238: #
2239: # a valid key looks like uname:udom#comments
2240: # comments are being appended
2241: #
1.498 www 2242: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2243: $kdom=
1.620 albertel 2244: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2245: $knum=
1.620 albertel 2246: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2247: $cdom=
1.620 albertel 2248: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2249: $cnum=
1.620 albertel 2250: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2251: $udom=$env{'user.name'} unless (defined($udom));
2252: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2253: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2254: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2255: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2256: # assigned to this person
2257: # - this should not happen,
1.345 www 2258: # unless something went wrong
2259: # the first time around
2260: # ready to assign
1.364 www 2261: $logentry=$1.'; '.$logentry;
1.496 www 2262: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2263: $kdom,$knum) eq 'ok') {
1.345 www 2264: # key now belongs to user
1.346 www 2265: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2266: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2267: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2268: return 'ok';
2269: } else {
2270: return
2271: 'error: Count not permanently assign key, will need to be re-entered later.';
2272: }
2273: } else {
2274: return 'error: Could not assign key, try again later.';
2275: }
1.364 www 2276: } elsif (!$existing{$ckey}) {
1.345 www 2277: # the key does not exist
2278: return 'error: The key does not exist';
2279: } else {
2280: # the key is somebody else's
2281: return 'error: The key is already in use';
2282: }
1.344 www 2283: }
2284:
1.364 www 2285: # ------------------------------------------ put an additional comment on a key
2286:
2287: sub comment_access_key {
2288: #
2289: # a valid key looks like uname:udom#comments
2290: # comments are being appended
2291: #
2292: my ($ckey,$cdom,$cnum,$logentry)=@_;
2293: $cdom=
1.620 albertel 2294: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2295: $cnum=
1.620 albertel 2296: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2297: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2298: if ($existing{$ckey}) {
2299: $existing{$ckey}.='; '.$logentry;
2300: # ready to assign
1.367 www 2301: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2302: $cdom,$cnum) eq 'ok') {
2303: return 'ok';
2304: } else {
2305: return 'error: Count not store comment.';
2306: }
2307: } else {
2308: # the key does not exist
2309: return 'error: The key does not exist';
2310: }
2311: }
2312:
1.344 www 2313: # ------------------------------------------------------ Generate a set of keys
2314:
2315: sub generate_access_keys {
1.364 www 2316: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2317: $cdom=
1.620 albertel 2318: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2319: $cnum=
1.620 albertel 2320: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2321: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2322: unless (($cdom) && ($cnum)) { return 0; }
2323: if ($number>10000) { return 0; }
2324: sleep(2); # make sure don't get same seed twice
2325: srand(time()^($$+($$<<15))); # from "Programming Perl"
2326: my $total=0;
2327: for (my $i=1;$i<=$number;$i++) {
2328: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2329: sprintf("%lx",int(100000*rand)).'-'.
2330: sprintf("%lx",int(100000*rand));
2331: $newkey=~s/1/g/g; # folks mix up 1 and l
2332: $newkey=~s/0/h/g; # and also 0 and O
2333: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2334: if ($existing{$newkey}) {
2335: $i--;
2336: } else {
1.364 www 2337: if (&put('accesskeys',
2338: { $newkey => '# generated '.localtime().
1.620 albertel 2339: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2340: '; '.$logentry },
2341: $cdom,$cnum) eq 'ok') {
1.344 www 2342: $total++;
2343: }
2344: }
2345: }
1.620 albertel 2346: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2347: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2348: return $total;
2349: }
2350:
2351: # ------------------------------------------------------- Validate an accesskey
2352:
2353: sub validate_access_key {
2354: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2355: $cdom=
1.620 albertel 2356: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2357: $cnum=
1.620 albertel 2358: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2359: $udom=$env{'user.domain'} unless (defined($udom));
2360: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2361: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2362: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2363: }
2364:
2365: # ------------------------------------- Find the section of student in a course
1.652 albertel 2366: sub devalidate_getsection_cache {
2367: my ($udom,$unam,$courseid)=@_;
2368: my $hashid="$udom:$unam:$courseid";
2369: &devalidate_cache_new('getsection',$hashid);
2370: }
1.298 matthew 2371:
1.815 albertel 2372: sub courseid_to_courseurl {
2373: my ($courseid) = @_;
2374: #already url style courseid
2375: return $courseid if ($courseid =~ m{^/});
2376:
2377: if (exists($env{'course.'.$courseid.'.num'})) {
2378: my $cnum = $env{'course.'.$courseid.'.num'};
2379: my $cdom = $env{'course.'.$courseid.'.domain'};
2380: return "/$cdom/$cnum";
2381: }
2382:
2383: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2384: if (exists($courseinfo{'num'})) {
2385: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2386: }
2387:
2388: return undef;
2389: }
2390:
1.298 matthew 2391: sub getsection {
2392: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2393: my $cachetime=1800;
1.551 albertel 2394:
2395: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2396: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2397: if (defined($cached)) { return $result; }
2398:
1.298 matthew 2399: my %Pending;
2400: my %Expired;
2401: #
2402: # Each role can either have not started yet (pending), be active,
2403: # or have expired.
2404: #
2405: # If there is an active role, we are done.
2406: #
2407: # If there is more than one role which has not started yet,
2408: # choose the one which will start sooner
2409: # If there is one role which has not started yet, return it.
2410: #
2411: # If there is more than one expired role, choose the one which ended last.
2412: # If there is a role which has expired, return it.
2413: #
1.815 albertel 2414: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2415: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2416: foreach my $key (keys(%roleshash)) {
1.479 albertel 2417: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2418: my $section=$1;
2419: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2420: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2421: my $now=time;
1.548 albertel 2422: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2423: $Expired{$end}=$section;
2424: next;
2425: }
1.548 albertel 2426: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2427: $Pending{$start}=$section;
2428: next;
2429: }
1.599 albertel 2430: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2431: }
2432: #
2433: # Presumedly there will be few matching roles from the above
2434: # loop and the sorting time will be negligible.
2435: if (scalar(keys(%Pending))) {
2436: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2437: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2438: }
2439: if (scalar(keys(%Expired))) {
2440: my @sorted = sort {$a <=> $b} keys(%Expired);
2441: my $time = pop(@sorted);
1.599 albertel 2442: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2443: }
1.599 albertel 2444: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2445: }
1.70 www 2446:
1.599 albertel 2447: sub save_cache {
2448: &purge_remembered();
1.722 albertel 2449: #&Apache::loncommon::validate_page();
1.620 albertel 2450: undef(%env);
1.780 albertel 2451: undef($env_loaded);
1.599 albertel 2452: }
1.452 albertel 2453:
1.599 albertel 2454: my $to_remember=-1;
2455: my %remembered;
2456: my %accessed;
2457: my $kicks=0;
2458: my $hits=0;
1.849 albertel 2459: sub make_key {
2460: my ($name,$id) = @_;
1.872 albertel 2461: if (length($id) > 65
2462: && length(&escape($id)) > 200) {
2463: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2464: }
1.849 albertel 2465: return &escape($name.':'.$id);
2466: }
2467:
1.599 albertel 2468: sub devalidate_cache_new {
2469: my ($name,$id,$debug) = @_;
2470: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2471: $id=&make_key($name,$id);
1.599 albertel 2472: $memcache->delete($id);
2473: delete($remembered{$id});
2474: delete($accessed{$id});
2475: }
2476:
2477: sub is_cached_new {
2478: my ($name,$id,$debug) = @_;
1.849 albertel 2479: $id=&make_key($name,$id);
1.599 albertel 2480: if (exists($remembered{$id})) {
1.1133 foxr 2481: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2482: $accessed{$id}=[&gettimeofday()];
2483: $hits++;
2484: return ($remembered{$id},1);
2485: }
2486: my $value = $memcache->get($id);
2487: if (!(defined($value))) {
2488: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2489: return (undef,undef);
1.416 albertel 2490: }
1.599 albertel 2491: if ($value eq '__undef__') {
2492: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2493: $value=undef;
2494: }
2495: &make_room($id,$value,$debug);
2496: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2497: return ($value,1);
2498: }
2499:
2500: sub do_cache_new {
2501: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2502: $id=&make_key($name,$id);
1.599 albertel 2503: my $setvalue=$value;
2504: if (!defined($setvalue)) {
2505: $setvalue='__undef__';
2506: }
1.623 albertel 2507: if (!defined($time) ) {
2508: $time=600;
2509: }
1.599 albertel 2510: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2511: my $result = $memcache->set($id,$setvalue,$time);
2512: if (! $result) {
1.872 albertel 2513: &logthis("caching of id -> $id failed");
1.910 albertel 2514: $memcache->disconnect_all();
1.872 albertel 2515: }
1.600 albertel 2516: # need to make a copy of $value
1.919 albertel 2517: &make_room($id,$value,$debug);
1.599 albertel 2518: return $value;
2519: }
2520:
2521: sub make_room {
2522: my ($id,$value,$debug)=@_;
1.919 albertel 2523:
2524: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2525: : $value;
1.599 albertel 2526: if ($to_remember<0) { return; }
2527: $accessed{$id}=[&gettimeofday()];
2528: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2529: my $to_kick;
2530: my $max_time=0;
2531: foreach my $other (keys(%accessed)) {
2532: if (&tv_interval($accessed{$other}) > $max_time) {
2533: $to_kick=$other;
2534: $max_time=&tv_interval($accessed{$other});
2535: }
2536: }
2537: delete($remembered{$to_kick});
2538: delete($accessed{$to_kick});
2539: $kicks++;
2540: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2541: return;
2542: }
2543:
1.599 albertel 2544: sub purge_remembered {
1.604 albertel 2545: #&logthis("Tossing ".scalar(keys(%remembered)));
2546: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2547: undef(%remembered);
2548: undef(%accessed);
1.428 albertel 2549: }
1.70 www 2550: # ------------------------------------- Read an entry from a user's environment
2551:
2552: sub userenvironment {
2553: my ($udom,$unam,@what)=@_;
1.976 raeburn 2554: my $items;
2555: foreach my $item (@what) {
2556: $items.=&escape($item).'&';
2557: }
2558: $items=~s/\&$//;
1.70 www 2559: my %returnhash=();
1.1009 raeburn 2560: my $uhome = &homeserver($unam,$udom);
2561: unless ($uhome eq 'no_host') {
2562: my @answer=split(/\&/,
2563: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2564: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2565: return %returnhash;
2566: }
1.1009 raeburn 2567: my $i;
2568: for ($i=0;$i<=$#what;$i++) {
2569: $returnhash{$what[$i]}=&unescape($answer[$i]);
2570: }
1.70 www 2571: }
2572: return %returnhash;
1.1 albertel 2573: }
2574:
1.617 albertel 2575: # ---------------------------------------------------------- Get a studentphoto
2576: sub studentphoto {
2577: my ($udom,$unam,$ext) = @_;
2578: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2579: if (defined($env{'request.course.id'})) {
1.708 raeburn 2580: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2581: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2582: return(&retrievestudentphoto($udom,$unam,$ext));
2583: } else {
2584: my ($result,$perm_reqd)=
1.707 albertel 2585: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2586: if ($result eq 'ok') {
2587: if (!($perm_reqd eq 'yes')) {
2588: return(&retrievestudentphoto($udom,$unam,$ext));
2589: }
2590: }
2591: }
2592: }
2593: } else {
2594: my ($result,$perm_reqd) =
1.707 albertel 2595: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2596: if ($result eq 'ok') {
2597: if (!($perm_reqd eq 'yes')) {
2598: return(&retrievestudentphoto($udom,$unam,$ext));
2599: }
2600: }
2601: }
2602: return '/adm/lonKaputt/lonlogo_broken.gif';
2603: }
2604:
2605: sub retrievestudentphoto {
2606: my ($udom,$unam,$ext,$type) = @_;
2607: my $home=&Apache::lonnet::homeserver($unam,$udom);
2608: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2609: if ($ret eq 'ok') {
2610: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2611: if ($type eq 'thumbnail') {
2612: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2613: }
2614: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2615: return $tokenurl;
2616: } else {
2617: if ($type eq 'thumbnail') {
2618: return '/adm/lonKaputt/genericstudent_tn.gif';
2619: } else {
2620: return '/adm/lonKaputt/lonlogo_broken.gif';
2621: }
1.617 albertel 2622: }
2623: }
2624:
1.263 www 2625: # -------------------------------------------------------------------- New chat
2626:
2627: sub chatsend {
1.724 raeburn 2628: my ($newentry,$anon,$group)=@_;
1.620 albertel 2629: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2630: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2631: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2632: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2633: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2634: &escape($newentry)).':'.$group,$chome);
1.292 www 2635: }
2636:
2637: # ------------------------------------------ Find current version of a resource
2638:
2639: sub getversion {
2640: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2641: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2642: return ¤tversion(&filelocation('',$fname));
2643: }
2644:
2645: sub currentversion {
2646: my $fname=shift;
2647: my $author=$fname;
2648: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2649: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2650: my $home=&homeserver($uname,$udom);
1.292 www 2651: if ($home eq 'no_host') {
2652: return -1;
2653: }
1.1112 www 2654: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2655: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2656: return -1;
2657: }
1.1112 www 2658: return $answer;
1.263 www 2659: }
2660:
1.1111 www 2661: #
2662: # Return special version number of resource if set by override, empty otherwise
2663: #
2664: sub usedversion {
2665: my $fname=shift;
2666: unless ($fname) { $fname=$env{'request.uri'}; }
2667: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2668: if ($urlversion) { return $urlversion; }
2669: return '';
2670: }
2671:
1.1 albertel 2672: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2673:
1.1 albertel 2674: sub subscribe {
2675: my $fname=shift;
1.761 raeburn 2676: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2677: $fname=~s/[\n\r]//g;
1.1 albertel 2678: my $author=$fname;
2679: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2680: my ($udom,$uname)=split(/\//,$author);
2681: my $home=homeserver($uname,$udom);
1.335 albertel 2682: if ($home eq 'no_host') {
2683: return 'not_found';
1.1 albertel 2684: }
2685: my $answer=reply("sub:$fname",$home);
1.64 www 2686: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2687: $answer.=' by '.$home;
2688: }
1.1 albertel 2689: return $answer;
2690: }
2691:
1.8 www 2692: # -------------------------------------------------------------- Replicate file
2693:
2694: sub repcopy {
2695: my $filename=shift;
1.23 www 2696: $filename=~s/\/+/\//g;
1.1142 raeburn 2697: my $londocroot = $perlvar{'lonDocRoot'};
2698: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2699: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2700: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2701: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2702: return &repcopy_userfile($filename);
2703: }
1.532 albertel 2704: $filename=~s/[\n\r]//g;
1.8 www 2705: my $transname="$filename.in.transfer";
1.828 www 2706: # FIXME: this should flock
1.607 raeburn 2707: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2708: my $remoteurl=subscribe($filename);
1.64 www 2709: if ($remoteurl =~ /^con_lost by/) {
2710: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2711: return 'unavailable';
1.8 www 2712: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2713: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2714: return 'not_found';
1.64 www 2715: } elsif ($remoteurl =~ /^rejected by/) {
2716: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2717: return 'forbidden';
1.20 www 2718: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2719: return 'ok';
1.8 www 2720: } else {
1.290 www 2721: my $author=$filename;
2722: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2723: my ($udom,$uname)=split(/\//,$author);
2724: my $home=homeserver($uname,$udom);
2725: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2726: my @parts=split(/\//,$filename);
2727: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2728: if ($path ne "$londocroot/res") {
1.8 www 2729: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2730: return 'bad_request';
1.8 www 2731: }
2732: my $count;
2733: for ($count=5;$count<$#parts;$count++) {
2734: $path.="/$parts[$count]";
2735: if ((-e $path)!=1) {
2736: mkdir($path,0777);
2737: }
2738: }
2739: my $ua=new LWP::UserAgent;
2740: my $request=new HTTP::Request('GET',"$remoteurl");
2741: my $response=$ua->request($request,$transname);
2742: if ($response->is_error()) {
2743: unlink($transname);
2744: my $message=$response->status_line;
1.672 albertel 2745: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2746: ." LWP get: $message: $filename</font>");
1.607 raeburn 2747: return 'unavailable';
1.8 www 2748: } else {
1.16 www 2749: if ($remoteurl!~/\.meta$/) {
2750: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2751: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2752: if ($mresponse->is_error()) {
2753: unlink($filename.'.meta');
2754: &logthis(
1.672 albertel 2755: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2756: }
2757: }
1.8 www 2758: rename($transname,$filename);
1.607 raeburn 2759: return 'ok';
1.8 www 2760: }
1.290 www 2761: }
1.8 www 2762: }
1.330 www 2763: }
2764:
2765: # ------------------------------------------------ Get server side include body
2766: sub ssi_body {
1.381 albertel 2767: my ($filelink,%form)=@_;
1.606 matthew 2768: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2769: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2770: }
1.953 www 2771: my $output='';
2772: my $response;
1.980 raeburn 2773: if ($filelink=~/^https?\:/) {
1.954 raeburn 2774: ($output,$response)=&externalssi($filelink);
1.953 www 2775: } else {
1.1004 droeschl 2776: $filelink .= $filelink=~/\?/ ? '&' : '?';
2777: $filelink .= 'inhibitmenu=yes';
1.953 www 2778: ($output,$response)=&ssi($filelink,%form);
2779: }
1.778 albertel 2780: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2781: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2782: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2783: if (wantarray) {
2784: return ($output, $response);
2785: } else {
2786: return $output;
2787: }
1.8 www 2788: }
2789:
1.15 www 2790: # --------------------------------------------------------- Server Side Include
2791:
1.782 albertel 2792: sub absolute_url {
2793: my ($host_name) = @_;
2794: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2795: if ($host_name eq '') {
2796: $host_name = $ENV{'SERVER_NAME'};
2797: }
2798: return $protocol.$host_name;
2799: }
2800:
1.942 foxr 2801: #
2802: # Server side include.
2803: # Parameters:
2804: # fn Possibly encrypted resource name/id.
2805: # form Hash that describes how the rendering should be done
2806: # and other things.
1.944 foxr 2807: # Returns:
1.950 raeburn 2808: # Scalar context: The content of the response.
2809: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2810: #
1.15 www 2811: sub ssi {
2812:
1.944 foxr 2813: my ($fn,%form)=@_;
1.15 www 2814: my $ua=new LWP::UserAgent;
1.23 www 2815: my $request;
1.711 albertel 2816:
2817: $form{'no_update_last_known'}=1;
1.895 albertel 2818: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2819: if (%form) {
1.782 albertel 2820: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58 raeburn 2821: $request->content(join('&',map {
2822: my $name = escape($_);
2823: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2824: ? join("&$name=", map {escape($_) } @{$form{$_}})
2825: : &escape($form{$_}) );
2826: } keys(%form)));
1.23 www 2827: } else {
1.782 albertel 2828: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2829: }
2830:
1.15 www 2831: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2832: my $response= $ua->request($request);
1.944 foxr 2833: if (wantarray) {
1.1172.2.3 raeburn 2834: return ($response->content, $response);
1.944 foxr 2835: } else {
1.1172.2.3 raeburn 2836: return $response->content;
1.942 foxr 2837: }
1.324 www 2838: }
2839:
2840: sub externalssi {
2841: my ($url)=@_;
2842: my $ua=new LWP::UserAgent;
2843: my $request=new HTTP::Request('GET',$url);
2844: my $response=$ua->request($request);
1.954 raeburn 2845: if (wantarray) {
2846: return ($response->content, $response);
2847: } else {
2848: return $response->content;
2849: }
1.15 www 2850: }
1.254 www 2851:
1.492 albertel 2852: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2853:
2854: sub allowuploaded {
2855: my ($srcurl,$url)=@_;
2856: $url=&clutter(&declutter($url));
2857: my $dir=$url;
2858: $dir=~s/\/[^\/]+$//;
2859: my %httpref=();
2860: my $httpurl=&hreflocation('',$url);
2861: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2862: &Apache::lonnet::appenv(\%httpref);
1.254 www 2863: }
1.477 raeburn 2864:
1.1172.2.13 raeburn 2865: #
2866: # Determine if the current user should be able to edit a particular resource,
2867: # when viewing in course context.
2868: # (a) When viewing resource used to determine if "Edit" item is included in
2869: # Functions.
2870: # (b) When displaying folder contents in course editor, used to determine if
2871: # "Edit" link will be displayed alongside resource.
2872: #
2873: # input: six args -- filename (decluttered), course number, course domain,
2874: # url, symb (if registered) and group (if this is a group
2875: # item -- e.g., bulletin board, group page etc.).
2876: # output: array of five scalars --
2877: # $cfile -- url for file editing if editable on current server
2878: # $home -- homeserver of resource (i.e., for author if published,
2879: # or course if uploaded.).
2880: # $switchserver -- 1 if server switch will be needed.
2881: # $forceedit -- 1 if icon/link should be to go to edit mode
2882: # $forceview -- 1 if icon/link should be to go to view mode
2883: #
2884:
2885: sub can_edit_resource {
2886: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2887: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2888: #
2889: # For aboutme pages user can only edit his/her own.
2890: #
2891: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2892: my ($sdom,$sname) = ($1,$2);
2893: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2894: $home = $env{'user.home'};
2895: $cfile = $resurl;
2896: if ($env{'form.forceedit'}) {
2897: $forceview = 1;
2898: } else {
2899: $forceedit = 1;
2900: }
2901: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2902: } else {
2903: return;
2904: }
2905: }
2906:
2907: if ($env{'request.course.id'}) {
2908: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2909: if ($group ne '') {
2910: # if this is a group homepage or group bulletin board, check group privs
2911: my $allowed = 0;
2912: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2913: if ((&allowed('mdg',$env{'request.course.id'}.
2914: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2915: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2916: $allowed = 1;
2917: }
2918: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2919: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2920: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2921: $allowed = 1;
2922: }
2923: }
2924: if ($allowed) {
2925: $home=&homeserver($cnum,$cdom);
2926: if ($env{'form.forceedit'}) {
2927: $forceview = 1;
2928: } else {
2929: $forceedit = 1;
2930: }
2931: $cfile = $resurl;
2932: } else {
2933: return;
2934: }
2935: } else {
1.1172.2.15 raeburn 2936: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2937: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2938: return;
2939: }
2940: } elsif (!$crsedit) {
1.1172.2.13 raeburn 2941: #
2942: # No edit allowed where CC has switched to student role.
2943: #
2944: return;
2945: }
2946: }
2947: }
2948:
2949: if ($file ne '') {
2950: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2951: if (&is_course_upload($file,$cnum,$cdom)) {
2952: $uploaded = 1;
2953: $incourse = 1;
2954: if ($file =~/\.(htm|html|css|js|txt)$/) {
2955: $cfile = &hreflocation('',$file);
2956: if ($env{'form.forceedit'}) {
2957: $forceview = 1;
2958: } else {
2959: $forceedit = 1;
2960: }
2961: }
2962: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2963: $incourse = 1;
2964: if ($env{'form.forceedit'}) {
2965: $forceview = 1;
2966: } else {
2967: $forceedit = 1;
2968: }
2969: $cfile = $resurl;
2970: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2971: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2972: $incourse = 1;
2973: if ($env{'form.forceedit'}) {
2974: $forceview = 1;
2975: } else {
2976: $forceedit = 1;
2977: }
2978: $cfile = $resurl;
2979: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2980: $incourse = 1;
2981: $cfile = $resurl.'/smpedit';
2982: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2983: $incourse = 1;
2984: if ($env{'form.forceedit'}) {
2985: $forceview = 1;
2986: } else {
2987: $forceedit = 1;
2988: }
2989: $cfile = $resurl;
1.1172.2.15 raeburn 2990: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2991: $incourse = 1;
2992: if ($env{'form.forceedit'}) {
2993: $forceview = 1;
2994: } else {
2995: $forceedit = 1;
2996: }
2997: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2998: }
2999: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3000: my $template = '/res/lib/templates/simpleproblem.problem';
3001: if (&is_on_map($template)) {
3002: $incourse = 1;
3003: $forceview = 1;
3004: $cfile = $template;
3005: }
3006: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3007: $incourse = 1;
3008: if ($env{'form.forceedit'}) {
3009: $forceview = 1;
3010: } else {
3011: $forceedit = 1;
3012: }
3013: $cfile = $resurl;
3014: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3015: $incourse = 1;
3016: $forceview = 1;
3017: if ($symb) {
3018: my ($map,$id,$res)=&decode_symb($symb);
3019: $env{'request.symb'} = $symb;
3020: $cfile = &clutter($res);
3021: } else {
3022: $cfile = $env{'form.suppurl'};
3023: $cfile =~ s{^http://}{};
3024: $cfile = '/adm/wrapper/ext/'.$cfile;
3025: }
1.1172.2.31 raeburn 3026: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3027: if ($env{'form.forceedit'}) {
3028: $forceview = 1;
3029: } else {
3030: $forceedit = 1;
3031: }
3032: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3033: }
3034: }
3035: if ($uploaded || $incourse) {
3036: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3037: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3038: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3039: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3040: # Check that the user has permission to edit this resource
3041: my $setpriv = 1;
3042: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3043: if (defined($cfudom)) {
3044: $home=&homeserver($cfuname,$cfudom);
3045: $cfile=$file;
3046: }
3047: }
3048: if (($cfile ne '') && (!$incourse || $uploaded) &&
3049: (($home ne '') && ($home ne 'no_host'))) {
3050: my @ids=¤t_machine_ids();
3051: unless (grep(/^\Q$home\E$/,@ids)) {
3052: $switchserver=1;
3053: }
3054: }
3055: }
3056: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3057: }
3058:
3059: sub is_course_upload {
3060: my ($file,$cnum,$cdom) = @_;
3061: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3062: $uploadpath =~ s{^\/}{};
3063: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3064: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3065: return 1;
3066: }
3067: return;
3068: }
3069:
3070: sub in_course {
3071: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3072: if ($hideprivileged) {
3073: my $skipuser;
1.1172.2.23 raeburn 3074: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3075: my @possdoms = ($cdom);
3076: if ($coursehash{'checkforpriv'}) {
3077: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3078: }
3079: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3080: $skipuser = 1;
3081: if ($coursehash{'nothideprivileged'}) {
3082: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3083: my $user;
3084: if ($item =~ /:/) {
3085: $user = $item;
3086: } else {
3087: $user = join(':',split(/[\@]/,$item));
3088: }
3089: if ($user eq $uname.':'.$udom) {
3090: undef($skipuser);
3091: last;
3092: }
3093: }
3094: }
3095: if ($skipuser) {
3096: return 0;
3097: }
3098: }
3099: }
3100: $type ||= 'any';
3101: if (!defined($cdom) || !defined($cnum)) {
3102: my $cid = $env{'request.course.id'};
3103: $cdom = $env{'course.'.$cid.'.domain'};
3104: $cnum = $env{'course.'.$cid.'.num'};
3105: }
3106: my $typesref;
3107: if (($type eq 'any') || ($type eq 'all')) {
3108: $typesref = ['active','previous','future'];
3109: } elsif ($type eq 'previous' || $type eq 'future') {
3110: $typesref = [$type];
3111: }
3112: my %roles = &get_my_roles($uname,$udom,'userroles',
3113: $typesref,undef,[$cdom]);
3114: my ($tmp) = keys(%roles);
3115: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3116: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3117: if (@course_roles > 0) {
3118: return 1;
3119: }
3120: return 0;
3121: }
3122:
1.478 albertel 3123: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3124: # input: action, courseID, current domain, intended
1.637 raeburn 3125: # path to file, source of file, instruction to parse file for objects,
3126: # ref to hash for embedded objects,
3127: # ref to hash for codebase of java objects.
1.1095 raeburn 3128: # reference to scalar to accommodate mime type determined
3129: # from File::MMagic if $parser = parse.
1.637 raeburn 3130: #
1.485 raeburn 3131: # output: url to file (if action was uploaddoc),
3132: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3133: #
1.478 albertel 3134: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3135: # course.
1.477 raeburn 3136: #
1.478 albertel 3137: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3138: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3139: # course's home server.
1.477 raeburn 3140: #
1.478 albertel 3141: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3142: # be copied from $source (current location) to
3143: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3144: # and will then be copied to
3145: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3146: # course's home server.
1.485 raeburn 3147: #
1.481 raeburn 3148: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3149: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3150: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3151: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3152: # in course's home server.
1.637 raeburn 3153: #
1.477 raeburn 3154:
3155: sub process_coursefile {
1.1095 raeburn 3156: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3157: $mimetype)=@_;
1.477 raeburn 3158: my $fetchresult;
1.638 albertel 3159: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3160: if ($action eq 'propagate') {
1.638 albertel 3161: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3162: $home);
1.481 raeburn 3163: } else {
1.477 raeburn 3164: my $fpath = '';
3165: my $fname = $file;
1.478 albertel 3166: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3167: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3168: my $filepath = &build_filepath($fpath);
1.481 raeburn 3169: if ($action eq 'copy') {
3170: if ($source eq '') {
3171: $fetchresult = 'no source file';
3172: return $fetchresult;
3173: } else {
3174: my $destination = $filepath.'/'.$fname;
3175: rename($source,$destination);
3176: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3177: $home);
1.481 raeburn 3178: }
3179: } elsif ($action eq 'uploaddoc') {
3180: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3181: print $fh $env{'form.'.$source};
1.481 raeburn 3182: close($fh);
1.637 raeburn 3183: if ($parser eq 'parse') {
1.1024 raeburn 3184: my $mm = new File::MMagic;
1.1095 raeburn 3185: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3186: if ($type eq 'text/html') {
1.1024 raeburn 3187: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3188: unless ($parse_result eq 'ok') {
3189: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3190: }
1.637 raeburn 3191: }
1.1095 raeburn 3192: if (ref($mimetype)) {
3193: $$mimetype = $type;
3194: }
1.637 raeburn 3195: }
1.477 raeburn 3196: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3197: $home);
1.481 raeburn 3198: if ($fetchresult eq 'ok') {
3199: return '/uploaded/'.$fpath.'/'.$fname;
3200: } else {
3201: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3202: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3203: return '/adm/notfound.html';
3204: }
1.477 raeburn 3205: }
3206: }
1.485 raeburn 3207: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3208: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3209: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3210: }
3211: return $fetchresult;
3212: }
3213:
1.637 raeburn 3214: sub build_filepath {
3215: my ($fpath) = @_;
3216: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3217: unless ($fpath eq '') {
3218: my @parts=split('/',$fpath);
3219: foreach my $part (@parts) {
3220: $filepath.= '/'.$part;
3221: if ((-e $filepath)!=1) {
3222: mkdir($filepath,0777);
3223: }
3224: }
3225: }
3226: return $filepath;
3227: }
3228:
3229: sub store_edited_file {
1.638 albertel 3230: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3231: my $file = $primary_url;
3232: $file =~ s#^/uploaded/$docudom/$docuname/##;
3233: my $fpath = '';
3234: my $fname = $file;
3235: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3236: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3237: my $filepath = &build_filepath($fpath);
3238: open(my $fh,'>'.$filepath.'/'.$fname);
3239: print $fh $content;
3240: close($fh);
1.638 albertel 3241: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3242: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3243: $home);
1.637 raeburn 3244: if ($$fetchresult eq 'ok') {
3245: return '/uploaded/'.$fpath.'/'.$fname;
3246: } else {
1.638 albertel 3247: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3248: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3249: return '/adm/notfound.html';
3250: }
3251: }
3252:
1.531 albertel 3253: sub clean_filename {
1.831 albertel 3254: my ($fname,$args)=@_;
1.315 www 3255: # Replace Windows backslashes by forward slashes
1.257 www 3256: $fname=~s/\\/\//g;
1.831 albertel 3257: if (!$args->{'keep_path'}) {
3258: # Get rid of everything but the actual filename
3259: $fname=~s/^.*\/([^\/]+)$/$1/;
3260: }
1.315 www 3261: # Replace spaces by underscores
3262: $fname=~s/\s+/\_/g;
3263: # Replace all other weird characters by nothing
1.831 albertel 3264: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3265: # Replace all .\d. sequences with _\d. so they no longer look like version
3266: # numbers
3267: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3268: return $fname;
3269: }
1.1051 raeburn 3270: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3271: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3272: # image with the same aspect ratio as the original, but with dimensions which do
3273: # not exceed $resizewidth and $resizeheight.
3274:
1.984 neumanie 3275: sub resizeImage {
1.1051 raeburn 3276: my ($img_path,$resizewidth,$resizeheight) = @_;
3277: my $ima = Image::Magick->new;
3278: my $resized;
3279: if (-e $img_path) {
3280: $ima->Read($img_path);
3281: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3282: my $width = $ima->Get('width');
3283: my $height = $ima->Get('height');
3284: if ($width > $resizewidth) {
3285: my $factor = $width/$resizewidth;
3286: my $newheight = $height/$factor;
3287: $ima->Scale(width=>$resizewidth,height=>$newheight);
3288: $resized = 1;
3289: }
3290: }
3291: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3292: my $width = $ima->Get('width');
3293: my $height = $ima->Get('height');
3294: if ($height > $resizeheight) {
3295: my $factor = $height/$resizeheight;
3296: my $newwidth = $width/$factor;
3297: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3298: $resized = 1;
3299: }
3300: }
3301: if ($resized) {
3302: $ima->Write($img_path);
3303: }
3304: }
3305: return;
1.977 amueller 3306: }
3307:
1.608 albertel 3308: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3309: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3310: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3311: # $context - possible values: coursedoc, existingfile, overwrite,
3312: # canceloverwrite, or ''.
3313: # if 'coursedoc': upload to the current course
3314: # if 'existingfile': write file to tmp/overwrites directory
3315: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3316: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3317: # $subdir - directory in userfile to store the file into
1.858 raeburn 3318: # $parser - instruction to parse file for objects ($parser = parse)
3319: # $allfiles - reference to hash for embedded objects
3320: # $codebase - reference to hash for codebase of java objects
3321: # $desuname - username for permanent storage of uploaded file
3322: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3323: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3324: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3325: # $resizewidth - width (pixels) to which to resize uploaded image
3326: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3327: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3328: # from File::MMagic.
1.858 raeburn 3329: #
1.686 albertel 3330: # output: url of file in userspace, or error: <message>
3331: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3332:
1.531 albertel 3333: sub userfileupload {
1.1090 raeburn 3334: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3335: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3336: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3337: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3338: $fname=&clean_filename($fname);
1.1090 raeburn 3339: # See if there is anything left
1.257 www 3340: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3341: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3342: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3343: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3344: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3345: my $now = time;
1.1090 raeburn 3346: my $filepath;
1.1095 raeburn 3347: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3348: $filepath = 'tmp/helprequests/'.$now;
3349: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3350: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3351: '_'.$env{'user.domain'}.'/pending';
3352: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3353: my ($docuname,$docudom);
3354: if ($destudom) {
3355: $docudom = $destudom;
3356: } else {
3357: $docudom = $env{'user.domain'};
3358: }
3359: if ($destuname) {
3360: $docuname = $destuname;
3361: } else {
3362: $docuname = $env{'user.name'};
3363: }
3364: if (exists($env{'form.group'})) {
3365: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3366: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3367: }
3368: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3369: if ($context eq 'canceloverwrite') {
3370: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3371: if (-e $tempfile) {
3372: my @info = stat($tempfile);
3373: if ($info[9] eq $env{'form.timestamp'}) {
3374: unlink($tempfile);
3375: }
3376: }
3377: return;
1.523 raeburn 3378: }
3379: }
1.1090 raeburn 3380: # Create the directory if not present
1.741 raeburn 3381: my @parts=split(/\//,$filepath);
3382: my $fullpath = $perlvar{'lonDaemons'};
3383: for (my $i=0;$i<@parts;$i++) {
3384: $fullpath .= '/'.$parts[$i];
3385: if ((-e $fullpath)!=1) {
3386: mkdir($fullpath,0777);
3387: }
3388: }
3389: open(my $fh,'>'.$fullpath.'/'.$fname);
3390: print $fh $env{'form.'.$formname};
3391: close($fh);
1.1090 raeburn 3392: if ($context eq 'existingfile') {
3393: my @info = stat($fullpath.'/'.$fname);
3394: return ($fullpath.'/'.$fname,$info[9]);
3395: } else {
3396: return $fullpath.'/'.$fname;
3397: }
1.523 raeburn 3398: }
1.995 raeburn 3399: if ($subdir eq 'scantron') {
3400: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3401: } else {
1.995 raeburn 3402: $fname="$subdir/$fname";
3403: }
1.1090 raeburn 3404: if ($context eq 'coursedoc') {
1.638 albertel 3405: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3406: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3407: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3408: return &finishuserfileupload($docuname,$docudom,
3409: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3410: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3411: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3412: } else {
1.1172.2.21 raeburn 3413: if ($env{'form.folder'}) {
3414: $fname=$env{'form.folder'}.'/'.$fname;
3415: }
1.638 albertel 3416: return &process_coursefile('uploaddoc',$docuname,$docudom,
3417: $fname,$formname,$parser,
1.1095 raeburn 3418: $allfiles,$codebase,$mimetype);
1.481 raeburn 3419: }
1.719 banghart 3420: } elsif (defined($destuname)) {
3421: my $docuname=$destuname;
3422: my $docudom=$destudom;
1.860 raeburn 3423: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3424: $parser,$allfiles,$codebase,
1.1051 raeburn 3425: $thumbwidth,$thumbheight,
1.1095 raeburn 3426: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3427: } else {
1.638 albertel 3428: my $docuname=$env{'user.name'};
3429: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3430: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3431: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3432: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3433: }
1.860 raeburn 3434: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3435: $parser,$allfiles,$codebase,
1.1051 raeburn 3436: $thumbwidth,$thumbheight,
1.1095 raeburn 3437: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3438: }
1.271 www 3439: }
3440:
3441: sub finishuserfileupload {
1.860 raeburn 3442: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3443: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3444: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3445: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3446:
1.860 raeburn 3447: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3448: $file=$fname;
3449: if ($fname=~m|/|) {
3450: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3451: $path.=$fnamepath.'/';
3452: }
1.259 www 3453: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3454: my $count;
3455: for ($count=4;$count<=$#parts;$count++) {
3456: $filepath.="/$parts[$count]";
3457: if ((-e $filepath)!=1) {
3458: mkdir($filepath,0777);
3459: }
3460: }
1.984 neumanie 3461:
1.258 www 3462: # Save the file
3463: {
1.701 albertel 3464: if (!open(FH,'>'.$filepath.'/'.$file)) {
3465: &logthis('Failed to create '.$filepath.'/'.$file);
3466: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3467: return '/adm/notfound.html';
3468: }
1.1090 raeburn 3469: if ($context eq 'overwrite') {
1.1117 foxr 3470: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3471: my $target = $filepath.'/'.$file;
3472: if (-e $source) {
3473: my @info = stat($source);
3474: if ($info[9] eq $env{'form.timestamp'}) {
3475: unless (&File::Copy::move($source,$target)) {
3476: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3477: return "Moving from $source failed";
3478: }
3479: } else {
3480: return "Temporary file: $source had unexpected date/time for last modification";
3481: }
3482: } else {
3483: return "Temporary file: $source missing";
3484: }
3485: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3486: &logthis('Failed to write to '.$filepath.'/'.$file);
3487: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3488: return '/adm/notfound.html';
3489: }
1.570 albertel 3490: close(FH);
1.1051 raeburn 3491: if ($resizewidth && $resizeheight) {
3492: my $mm = new File::MMagic;
3493: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3494: if ($mime_type =~ m{^image/}) {
3495: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3496: }
1.977 amueller 3497: }
1.258 www 3498: }
1.1152 raeburn 3499: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3500: if (ref($mimetype)) {
3501: if ($$mimetype eq '') {
3502: my $mm = new File::MMagic;
3503: my $type = $mm->checktype_filename($filepath.'/'.$file);
3504: $$mimetype = $type;
3505: }
3506: }
3507: }
1.637 raeburn 3508: if ($parser eq 'parse') {
1.1152 raeburn 3509: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3510: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3511: $allfiles,$codebase);
3512: unless ($parse_result eq 'ok') {
3513: &logthis('Failed to parse '.$filepath.$file.
3514: ' for embedded media: '.$parse_result);
3515: }
1.637 raeburn 3516: }
3517: }
1.860 raeburn 3518: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3519: my $input = $filepath.'/'.$file;
3520: my $output = $filepath.'/'.'tn-'.$file;
3521: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3522: system("convert -sample $thumbsize $input $output");
3523: if (-e $filepath.'/'.'tn-'.$file) {
3524: $fetchthumb = 1;
3525: }
3526: }
1.858 raeburn 3527:
1.259 www 3528: # Notify homeserver to grep it
3529: #
1.984 neumanie 3530: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3531: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3532: if ($fetchresult eq 'ok') {
1.860 raeburn 3533: if ($fetchthumb) {
3534: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3535: if ($thumbresult ne 'ok') {
3536: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3537: $docuhome.': '.$thumbresult);
3538: }
3539: }
1.259 www 3540: #
1.258 www 3541: # Return the URL to it
1.494 albertel 3542: return '/uploaded/'.$path.$file;
1.263 www 3543: } else {
1.494 albertel 3544: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3545: ': '.$fetchresult);
1.263 www 3546: return '/adm/notfound.html';
1.858 raeburn 3547: }
1.493 albertel 3548: }
3549:
1.637 raeburn 3550: sub extract_embedded_items {
1.961 raeburn 3551: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3552: my @state = ();
1.1164 raeburn 3553: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3554: my %javafiles = (
3555: codebase => '',
3556: code => '',
3557: archive => ''
3558: );
3559: my %mediafiles = (
3560: src => '',
3561: movie => '',
3562: );
1.648 raeburn 3563: my $p;
3564: if ($content) {
3565: $p = HTML::LCParser->new($content);
3566: } else {
1.961 raeburn 3567: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3568: }
1.641 albertel 3569: while (my $t=$p->get_token()) {
1.640 albertel 3570: if ($t->[0] eq 'S') {
3571: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3572: push(@state, $tagname);
1.648 raeburn 3573: if (lc($tagname) eq 'allow') {
3574: &add_filetype($allfiles,$attr->{'src'},'src');
3575: }
1.640 albertel 3576: if (lc($tagname) eq 'img') {
3577: &add_filetype($allfiles,$attr->{'src'},'src');
3578: }
1.886 albertel 3579: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3580: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3581: &add_filetype($allfiles,$attr->{'href'},'href');
3582: }
1.886 albertel 3583: }
1.645 raeburn 3584: if (lc($tagname) eq 'script') {
1.1164 raeburn 3585: my $src;
1.645 raeburn 3586: if ($attr->{'archive'} =~ /\.jar$/i) {
3587: &add_filetype($allfiles,$attr->{'archive'},'archive');
3588: } else {
1.1164 raeburn 3589: if ($attr->{'src'} ne '') {
3590: $src = $attr->{'src'};
3591: &add_filetype($allfiles,$src,'src');
3592: }
3593: }
3594: my $text = $p->get_trimmed_text();
3595: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3596: my @swfargs = split(/,/,$1);
3597: foreach my $item (@swfargs) {
3598: $item =~ s/["']//g;
3599: $item =~ s/^\s+//;
3600: $item =~ s/\s+$//;
3601: }
3602: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3603: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3604: push(@{$related{$swfargs[0]}},$swfargs[2]);
3605: } else {
3606: $related{$swfargs[0]} = [$swfargs[2]];
3607: }
3608: }
1.645 raeburn 3609: }
3610: }
3611: if (lc($tagname) eq 'link') {
3612: if (lc($attr->{'rel'}) eq 'stylesheet') {
3613: &add_filetype($allfiles,$attr->{'href'},'href');
3614: }
3615: }
1.640 albertel 3616: if (lc($tagname) eq 'object' ||
3617: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3618: foreach my $item (keys(%javafiles)) {
3619: $javafiles{$item} = '';
3620: }
1.1164 raeburn 3621: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3622: $lastids{lc($tagname)} = $attr->{'id'};
3623: }
1.640 albertel 3624: }
3625: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3626: my $name = lc($attr->{'name'});
3627: foreach my $item (keys(%javafiles)) {
3628: if ($name eq $item) {
3629: $javafiles{$item} = $attr->{'value'};
3630: last;
3631: }
3632: }
1.1164 raeburn 3633: my $pathfrom;
1.640 albertel 3634: foreach my $item (keys(%mediafiles)) {
3635: if ($name eq $item) {
1.1164 raeburn 3636: $pathfrom = $attr->{'value'};
3637: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3638: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3639: last;
3640: }
3641: }
1.1164 raeburn 3642: if ($name eq 'flashvars') {
3643: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3644: }
3645: if ($pathfrom ne '') {
3646: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3647: $pathfrom);
3648: }
1.640 albertel 3649: }
3650: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3651: foreach my $item (keys(%javafiles)) {
3652: if ($attr->{$item}) {
3653: $javafiles{$item} = $attr->{$item};
3654: last;
3655: }
3656: }
3657: foreach my $item (keys(%mediafiles)) {
3658: if ($attr->{$item}) {
3659: &add_filetype($allfiles,$attr->{$item},$item);
3660: last;
3661: }
3662: }
1.1164 raeburn 3663: if (lc($tagname) eq 'embed') {
3664: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3665: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3666: $attr->{'src'});
3667: }
3668: }
1.640 albertel 3669: }
1.1172.2.35 raeburn 3670: if (lc($tagname) eq 'iframe') {
3671: my $src = $attr->{'src'} ;
3672: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3673: &add_filetype($allfiles,$src,'src');
3674: } elsif ($src =~ m{^/}) {
3675: if ($env{'request.course.id'}) {
3676: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3677: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3678: my $url = &hreflocation('',$fullpath);
3679: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3680: my $relpath = $1;
3681: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3682: &add_filetype($allfiles,$1,'src');
3683: }
3684: }
3685: }
3686: }
3687: }
1.1164 raeburn 3688: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3689: pop(@state);
1.1164 raeburn 3690: }
1.640 albertel 3691: } elsif ($t->[0] eq 'E') {
3692: my ($tagname) = ($t->[1]);
3693: if ($javafiles{'codebase'} ne '') {
3694: $javafiles{'codebase'} .= '/';
3695: }
3696: if (lc($tagname) eq 'applet' ||
3697: lc($tagname) eq 'object' ||
3698: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3699: ) {
3700: foreach my $item (keys(%javafiles)) {
3701: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3702: my $file=$javafiles{'codebase'}.$javafiles{$item};
3703: &add_filetype($allfiles,$file,$item);
3704: }
3705: }
3706: }
3707: pop @state;
3708: }
3709: }
1.1164 raeburn 3710: foreach my $id (sort(keys(%flashvars))) {
3711: if ($shockwave{$id} ne '') {
3712: my @pairs = split(/\&/,$flashvars{$id});
3713: foreach my $pair (@pairs) {
3714: my ($key,$value) = split(/\=/,$pair);
3715: if ($key eq 'thumb') {
3716: &add_filetype($allfiles,$value,$key);
3717: } elsif ($key eq 'content') {
3718: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3719: my ($ext) = ($value =~ /\.([^.]+)$/);
3720: if ($ext ne '') {
3721: &add_filetype($allfiles,$path.$value,$ext);
3722: }
3723: }
3724: }
3725: }
3726: }
1.637 raeburn 3727: return 'ok';
3728: }
3729:
1.639 albertel 3730: sub add_filetype {
3731: my ($allfiles,$file,$type)=@_;
3732: if (exists($allfiles->{$file})) {
3733: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3734: push(@{$allfiles->{$file}}, &escape($type));
3735: }
3736: } else {
3737: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3738: }
3739: }
3740:
1.1164 raeburn 3741: sub embedded_dependency {
3742: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3743: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3744: if (($identifier ne '') &&
3745: (ref($related->{$identifier}) eq 'ARRAY') &&
3746: ($pathfrom ne '')) {
3747: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3748: foreach my $dep (@{$related->{$identifier}}) {
3749: &add_filetype($allfiles,$path.$dep,'object');
3750: }
3751: }
3752: }
3753: return;
3754: }
3755:
1.493 albertel 3756: sub removeuploadedurl {
1.984 neumanie 3757: my ($url)=@_;
3758: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3759: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3760: }
3761:
3762: sub removeuserfile {
3763: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3764: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3765: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3766: if ($result eq 'ok') {
1.798 raeburn 3767: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3768: my $metafile = $fname.'.meta';
3769: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3770: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3771: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3772: my $sqlresult =
1.823 albertel 3773: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3774: 'portfolio_metadata',$group,
3775: 'delete');
1.798 raeburn 3776: }
3777: }
3778: return $result;
1.257 www 3779: }
1.15 www 3780:
1.530 albertel 3781: sub mkdiruserfile {
3782: my ($docuname,$docudom,$dir)=@_;
3783: my $home=&homeserver($docuname,$docudom);
3784: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3785: }
3786:
1.531 albertel 3787: sub renameuserfile {
3788: my ($docuname,$docudom,$old,$new)=@_;
3789: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3790: my $result = &reply("renameuserfile:$docudom:$docuname:".
3791: &escape("$old").':'.&escape("$new"),$home);
3792: if ($result eq 'ok') {
3793: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3794: my $oldmeta = $old.'.meta';
3795: my $newmeta = $new.'.meta';
3796: my $metaresult =
3797: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3798: my $url = "/uploaded/$docudom/$docuname/$old";
3799: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3800: my $sqlresult =
1.823 albertel 3801: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3802: 'portfolio_metadata',$group,
3803: 'delete');
1.798 raeburn 3804: }
3805: }
3806: return $result;
1.531 albertel 3807: }
3808:
1.14 www 3809: # ------------------------------------------------------------------------- Log
3810:
3811: sub log {
3812: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3813: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3814: }
3815:
3816: # ------------------------------------------------------------------ Course Log
1.352 www 3817: #
3818: # This routine flushes several buffers of non-mission-critical nature
3819: #
1.157 www 3820:
3821: sub flushcourselogs {
1.352 www 3822: &logthis('Flushing log buffers');
3823: #
3824: # course logs
3825: # This is a log of all transactions in a course, which can be used
3826: # for data mining purposes
3827: #
3828: # It also collects the courseid database, which lists last transaction
3829: # times and course titles for all courseids
3830: #
3831: my %courseidbuffer=();
1.921 raeburn 3832: foreach my $crsid (keys(%courselogs)) {
1.352 www 3833: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3834: &escape($courselogs{$crsid}),
3835: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3836: delete $courselogs{$crsid};
3837: } else {
3838: &logthis('Failed to flush log buffer for '.$crsid);
3839: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3840: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3841: " exceeded maximum size, deleting.</font>");
3842: delete $courselogs{$crsid};
3843: }
1.352 www 3844: }
1.920 raeburn 3845: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3846: 'description' => $coursedescrbuf{$crsid},
3847: 'inst_code' => $courseinstcodebuf{$crsid},
3848: 'type' => $coursetypebuf{$crsid},
3849: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3850: };
1.191 harris41 3851: }
1.352 www 3852: #
3853: # Write course id database (reverse lookup) to homeserver of courses
3854: # Is used in pickcourse
3855: #
1.840 albertel 3856: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3857: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3858: $courseidbuffer{$crs_home},
3859: $crs_home,'timeonly');
1.352 www 3860: }
3861: #
3862: # File accesses
3863: # Writes to the dynamic metadata of resources to get hit counts, etc.
3864: #
1.449 matthew 3865: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3866: if ($entry =~ /___count$/) {
3867: my ($dom,$name);
1.807 albertel 3868: ($dom,$name,undef)=
1.811 albertel 3869: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3870: if (! defined($dom) || $dom eq '' ||
3871: ! defined($name) || $name eq '') {
1.620 albertel 3872: my $cid = $env{'request.course.id'};
3873: $dom = $env{'request.'.$cid.'.domain'};
3874: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3875: }
1.450 matthew 3876: my $value = $accesshash{$entry};
3877: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3878: my %temphash=($url => $value);
1.449 matthew 3879: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3880: if ($result eq 'ok') {
3881: delete $accesshash{$entry};
3882: }
3883: } else {
1.811 albertel 3884: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3885: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3886: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3887: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3888: delete $accesshash{$entry};
3889: }
1.185 www 3890: }
1.191 harris41 3891: }
1.352 www 3892: #
3893: # Roles
3894: # Reverse lookup of user roles for course faculty/staff and co-authorship
3895: #
1.800 albertel 3896: foreach my $entry (keys(%userrolehash)) {
1.351 www 3897: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3898: split(/\:/,$entry);
3899: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3900: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3901: $rudom,$runame) eq 'ok') {
3902: delete $userrolehash{$entry};
3903: }
3904: }
1.662 raeburn 3905: #
3906: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3907: #
3908: my %domrolebuffer = ();
1.1000 raeburn 3909: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3910: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3911: if ($domrolebuffer{$rudom}) {
3912: $domrolebuffer{$rudom}.='&'.&escape($entry).
3913: '='.&escape($domainrolehash{$entry});
3914: } else {
3915: $domrolebuffer{$rudom}.=&escape($entry).
3916: '='.&escape($domainrolehash{$entry});
3917: }
3918: delete $domainrolehash{$entry};
3919: }
3920: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3921: my %servers = &get_servers($dom,'library');
3922: foreach my $tryserver (keys(%servers)) {
3923: unless (&reply('domroleput:'.$dom.':'.
3924: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3925: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3926: }
1.662 raeburn 3927: }
3928: }
1.186 www 3929: $dumpcount++;
1.157 www 3930: }
3931:
3932: sub courselog {
3933: my $what=shift;
1.158 www 3934: $what=time.':'.$what;
1.620 albertel 3935: unless ($env{'request.course.id'}) { return ''; }
3936: $coursedombuf{$env{'request.course.id'}}=
3937: $env{'course.'.$env{'request.course.id'}.'.domain'};
3938: $coursenumbuf{$env{'request.course.id'}}=
3939: $env{'course.'.$env{'request.course.id'}.'.num'};
3940: $coursehombuf{$env{'request.course.id'}}=
3941: $env{'course.'.$env{'request.course.id'}.'.home'};
3942: $coursedescrbuf{$env{'request.course.id'}}=
3943: $env{'course.'.$env{'request.course.id'}.'.description'};
3944: $courseinstcodebuf{$env{'request.course.id'}}=
3945: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3946: $courseownerbuf{$env{'request.course.id'}}=
3947: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3948: $coursetypebuf{$env{'request.course.id'}}=
3949: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3950: if (defined $courselogs{$env{'request.course.id'}}) {
3951: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3952: } else {
1.620 albertel 3953: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3954: }
1.620 albertel 3955: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3956: &flushcourselogs();
3957: }
1.158 www 3958: }
3959:
3960: sub courseacclog {
3961: my $fnsymb=shift;
1.620 albertel 3962: unless ($env{'request.course.id'}) { return ''; }
3963: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3964: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3965: $what.=':POST';
1.583 matthew 3966: # FIXME: Probably ought to escape things....
1.800 albertel 3967: foreach my $key (keys(%env)) {
3968: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3969: my $formitem = $1;
3970: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3971: $what.=':'.$formitem.'='.$env{$key};
3972: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3973: $what.=':'.$formitem.'='.$env{$key};
3974: }
1.158 www 3975: }
1.191 harris41 3976: }
1.583 matthew 3977: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3978: # FIXME: We should not be depending on a form parameter that someone
3979: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3980: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3981: $what.= ':POST';
3982: # FIXME: Probably ought to escape things....
3983: foreach my $element ('courseexp','crsfulltext','crsrelated',
3984: 'crsdiscuss') {
1.620 albertel 3985: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3986: }
3987: }
1.158 www 3988: }
3989: &courselog($what);
1.149 www 3990: }
3991:
1.185 www 3992: sub countacc {
3993: my $url=&declutter(shift);
1.458 matthew 3994: return if (! defined($url) || $url eq '');
1.620 albertel 3995: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3996: #
3997: # Mark that this url was used in this course
3998: #
1.620 albertel 3999: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4000: #
4001: # Increase the access count for this resource in this child process
4002: #
1.281 www 4003: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4004: $accesshash{$key}++;
1.185 www 4005: }
1.349 www 4006:
1.361 www 4007: sub linklog {
4008: my ($from,$to)=@_;
4009: $from=&declutter($from);
4010: $to=&declutter($to);
4011: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4012: $accesshash{$to.'___'.$from.'___goto'}=1;
4013: }
1.1160 www 4014:
4015: sub statslog {
4016: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4017: if ($users<2) { return; }
4018: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4019: 'course' => $env{'request.course.id'},
4020: 'sections' => '"all"',
4021: 'num_students' => $users,
4022: 'part' => $part,
4023: 'symb' => $symb,
4024: 'mean_tries' => $av_attempts,
4025: 'deg_of_diff' => $degdiff});
4026: foreach my $key (keys(%dynstore)) {
4027: $accesshash{$key}=$dynstore{$key};
4028: }
4029: }
1.361 www 4030:
1.349 www 4031: sub userrolelog {
4032: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4033: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4034: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4035: $userrolehash
4036: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4037: =$tend.':'.$tstart;
1.662 raeburn 4038: }
1.1169 droeschl 4039: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4040: $userrolehash
4041: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4042: =$tend.':'.$tstart;
4043: }
1.1169 droeschl 4044: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 4045: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4046: $domainrolehash
4047: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4048: = $tend.':'.$tstart;
4049: }
1.351 www 4050: }
4051:
1.957 raeburn 4052: sub courserolelog {
4053: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4054: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4055: my $cdom = $1;
4056: my $cnum = $2;
4057: my $sec = $3;
4058: my $namespace = 'rolelog';
4059: my %storehash = (
4060: role => $trole,
4061: start => $tstart,
4062: end => $tend,
4063: selfenroll => $selfenroll,
4064: context => $context,
4065: );
4066: if ($trole eq 'gr') {
4067: $namespace = 'groupslog';
4068: $storehash{'group'} = $sec;
4069: } else {
4070: $storehash{'section'} = $sec;
4071: }
4072: &write_log('course',$namespace,\%storehash,$delflag,$username,
4073: $domain,$cnum,$cdom);
4074: if (($trole ne 'st') || ($sec ne '')) {
4075: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4076: }
4077: }
4078: return;
4079: }
4080:
1.1172.2.9 raeburn 4081: sub domainrolelog {
4082: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4083: if ($area =~ m{^/($match_domain)/$}) {
4084: my $cdom = $1;
4085: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4086: my $namespace = 'rolelog';
4087: my %storehash = (
4088: role => $trole,
4089: start => $tstart,
4090: end => $tend,
4091: context => $context,
4092: );
4093: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4094: $domain,$domconfiguser,$cdom);
4095: }
4096: return;
4097:
4098: }
4099:
4100: sub coauthorrolelog {
4101: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4102: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4103: my $audom = $1;
4104: my $auname = $2;
4105: my $namespace = 'rolelog';
4106: my %storehash = (
4107: role => $trole,
4108: start => $tstart,
4109: end => $tend,
4110: context => $context,
4111: );
4112: &write_log('author',$namespace,\%storehash,$delflag,$username,
4113: $domain,$auname,$audom);
4114: }
4115: return;
4116: }
4117:
1.351 www 4118: sub get_course_adv_roles {
1.948 raeburn 4119: my ($cid,$codes) = @_;
1.620 albertel 4120: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4121: my %coursehash=&coursedescription($cid);
1.988 raeburn 4122: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4123: my %nothide=();
1.800 albertel 4124: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4125: if ($user !~ /:/) {
4126: $nothide{join(':',split(/[\@]/,$user))}=1;
4127: } else {
4128: $nothide{$user}=1;
4129: }
1.470 www 4130: }
1.1172.2.23 raeburn 4131: my @possdoms = ($coursehash{'domain'});
4132: if ($coursehash{'checkforpriv'}) {
4133: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4134: }
1.351 www 4135: my %returnhash=();
4136: my %dumphash=
4137: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4138: my $now=time;
1.997 raeburn 4139: my %privileged;
1.1000 raeburn 4140: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4141: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4142: if (($tstart) && ($tstart<0)) { next; }
4143: if (($tend) && ($tend<$now)) { next; }
4144: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4145: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4146: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4147: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4148: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4149: if ($role eq 'cr') { next; }
1.948 raeburn 4150: if ($codes) {
4151: if ($section) { $role .= ':'.$section; }
4152: if ($returnhash{$role}) {
4153: $returnhash{$role}.=','.$username.':'.$domain;
4154: } else {
4155: $returnhash{$role}=$username.':'.$domain;
4156: }
1.351 www 4157: } else {
1.988 raeburn 4158: my $key=&plaintext($role,$crstype);
1.973 bisitz 4159: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4160: if ($returnhash{$key}) {
4161: $returnhash{$key}.=','.$username.':'.$domain;
4162: } else {
4163: $returnhash{$key}=$username.':'.$domain;
4164: }
1.351 www 4165: }
1.948 raeburn 4166: }
1.400 www 4167: return %returnhash;
4168: }
4169:
4170: sub get_my_roles {
1.937 raeburn 4171: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4172: unless (defined($uname)) { $uname=$env{'user.name'}; }
4173: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4174: my (%dumphash,%nothide);
1.1086 raeburn 4175: if ($context eq 'userroles') {
1.1166 raeburn 4176: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4177: } else {
1.1172.2.23 raeburn 4178: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4179: if ($hidepriv) {
4180: my %coursehash=&coursedescription($udom.'_'.$uname);
4181: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4182: if ($user !~ /:/) {
4183: $nothide{join(':',split(/[\@]/,$user))} = 1;
4184: } else {
4185: $nothide{$user} = 1;
4186: }
4187: }
4188: }
1.858 raeburn 4189: }
1.400 www 4190: my %returnhash=();
4191: my $now=time;
1.999 raeburn 4192: my %privileged;
1.800 albertel 4193: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4194: my ($role,$tend,$tstart);
4195: if ($context eq 'userroles') {
1.1149 raeburn 4196: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4197: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4198: } else {
4199: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4200: }
1.400 www 4201: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4202: my $status = 'active';
1.939 raeburn 4203: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4204: $status = 'previous';
4205: }
4206: if (($tstart) && ($now<$tstart)) {
4207: $status = 'future';
4208: }
4209: if (ref($types) eq 'ARRAY') {
4210: if (!grep(/^\Q$status\E$/,@{$types})) {
4211: next;
4212: }
4213: } else {
4214: if ($status ne 'active') {
4215: next;
4216: }
4217: }
1.867 raeburn 4218: my ($rolecode,$username,$domain,$section,$area);
4219: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4220: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4221: (undef,$domain,$username,$section) = split(/\//,$area);
4222: } else {
4223: ($role,$username,$domain,$section) = split(/\:/,$entry);
4224: }
1.832 raeburn 4225: if (ref($roledoms) eq 'ARRAY') {
4226: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4227: next;
4228: }
4229: }
4230: if (ref($roles) eq 'ARRAY') {
4231: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4232: if ($role =~ /^cr\//) {
4233: if (!grep(/^cr$/,@{$roles})) {
4234: next;
4235: }
1.1104 raeburn 4236: } elsif ($role =~ /^gr\//) {
4237: if (!grep(/^gr$/,@{$roles})) {
4238: next;
4239: }
1.922 raeburn 4240: } else {
4241: next;
4242: }
1.832 raeburn 4243: }
1.867 raeburn 4244: }
1.937 raeburn 4245: if ($hidepriv) {
1.1172.2.23 raeburn 4246: my @privroles = ('dc','su');
1.999 raeburn 4247: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4248: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4249: } else {
1.1172.2.23 raeburn 4250: my $possdoms = [$domain];
4251: if (ref($roledoms) eq 'ARRAY') {
4252: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4253: }
1.1172.2.23 raeburn 4254: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4255: if (!$nothide{$username.':'.$domain}) {
4256: next;
4257: }
4258: }
1.937 raeburn 4259: }
4260: }
1.933 raeburn 4261: if ($withsec) {
4262: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4263: $tstart.':'.$tend;
4264: } else {
4265: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4266: }
1.832 raeburn 4267: }
1.373 www 4268: return %returnhash;
1.399 www 4269: }
4270:
4271: # ----------------------------------------------------- Frontpage Announcements
4272: #
4273: #
4274:
4275: sub postannounce {
4276: my ($server,$text)=@_;
1.844 albertel 4277: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4278: unless ($text=~/\w/) { $text=''; }
4279: return &reply('setannounce:'.&escape($text),$server);
4280: }
4281:
4282: sub getannounce {
1.448 albertel 4283:
4284: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4285: my $announcement='';
1.800 albertel 4286: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4287: close($fh);
1.399 www 4288: if ($announcement=~/\w/) {
4289: return
4290: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4291: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4292: } else {
4293: return '';
4294: }
4295: } else {
4296: return '';
4297: }
1.351 www 4298: }
1.353 www 4299:
4300: # ---------------------------------------------------------- Course ID routines
4301: # Deal with domain's nohist_courseid.db files
4302: #
4303:
4304: sub courseidput {
1.921 raeburn 4305: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4306: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4307: my $outcome;
4308: if ($caller eq 'timeonly') {
4309: my $cids = '';
4310: foreach my $item (keys(%$storehash)) {
4311: $cids.=&escape($item).'&';
4312: }
4313: $cids=~s/\&$//;
4314: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4315: $coursehome);
4316: } else {
4317: my $items = '';
4318: foreach my $item (keys(%$storehash)) {
4319: $items.= &escape($item).'='.
4320: &freeze_escape($$storehash{$item}).'&';
4321: }
4322: $items=~s/\&$//;
4323: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4324: $coursehome);
1.918 raeburn 4325: }
4326: if ($outcome eq 'unknown_cmd') {
4327: my $what;
4328: foreach my $cid (keys(%$storehash)) {
4329: $what .= &escape($cid).'=';
1.921 raeburn 4330: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4331: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4332: }
4333: $what =~ s/\:$/&/;
4334: }
4335: $what =~ s/\&$//;
4336: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4337: } else {
4338: return $outcome;
4339: }
1.353 www 4340: }
4341:
4342: sub courseiddump {
1.921 raeburn 4343: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4344: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4345: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 4346: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 4347: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4348: my $as_hash = 1;
4349: my %returnhash;
4350: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4351: my %libserv = &all_library();
4352: foreach my $tryserver (keys(%libserv)) {
4353: if ( ( $hostidflag == 1
4354: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4355: || (!defined($hostidflag)) ) {
4356:
1.918 raeburn 4357: if (($domfilter eq '') ||
4358: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4359: my $rep;
4360: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4361: $rep = &LONCAPA::Lond::dump_course_id_handler(
4362: join(":", (&host_domain($tryserver), $sincefilter,
4363: &escape($descfilter), &escape($instcodefilter),
4364: &escape($ownerfilter), &escape($coursefilter),
4365: &escape($typefilter), &escape($regexp_ok),
4366: $as_hash, &escape($selfenrollonly),
4367: &escape($catfilter), $showhidden, $caller,
4368: &escape($cloner), &escape($cc_clone), $cloneonly,
4369: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 4370: &escape($creationcontext),$domcloner,$hasuniquecode,
4371: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 4372: } else {
4373: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4374: $sincefilter.':'.&escape($descfilter).':'.
4375: &escape($instcodefilter).':'.&escape($ownerfilter).
4376: ':'.&escape($coursefilter).':'.&escape($typefilter).
4377: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4378: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4379: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4380: &escape($cc_clone).':'.$cloneonly.':'.
4381: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 4382: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4383: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 4384: }
4385:
1.918 raeburn 4386: my @pairs=split(/\&/,$rep);
4387: foreach my $item (@pairs) {
4388: my ($key,$value)=split(/\=/,$item,2);
4389: $key = &unescape($key);
4390: next if ($key =~ /^error: 2 /);
4391: my $result = &thaw_unescape($value);
4392: if (ref($result) eq 'HASH') {
4393: $returnhash{$key}=$result;
4394: } else {
1.921 raeburn 4395: my @responses = split(/:/,$value);
4396: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4397: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4398: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4399: }
1.1008 raeburn 4400: }
1.353 www 4401: }
4402: }
4403: }
4404: }
4405: return %returnhash;
4406: }
4407:
1.1055 raeburn 4408: sub courselastaccess {
4409: my ($cdom,$cnum,$hostidref) = @_;
4410: my %returnhash;
4411: if ($cdom && $cnum) {
4412: my $chome = &homeserver($cnum,$cdom);
4413: if ($chome ne 'no_host') {
4414: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4415: &extract_lastaccess(\%returnhash,$rep);
4416: }
4417: } else {
4418: if (!$cdom) { $cdom=''; }
4419: my %libserv = &all_library();
4420: foreach my $tryserver (keys(%libserv)) {
4421: if (ref($hostidref) eq 'ARRAY') {
4422: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4423: }
4424: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4425: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4426: &extract_lastaccess(\%returnhash,$rep);
4427: }
4428: }
4429: }
4430: return %returnhash;
4431: }
4432:
4433: sub extract_lastaccess {
4434: my ($returnhash,$rep) = @_;
4435: if (ref($returnhash) eq 'HASH') {
4436: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4437: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4438: $rep eq '') {
4439: my @pairs=split(/\&/,$rep);
4440: foreach my $item (@pairs) {
4441: my ($key,$value)=split(/\=/,$item,2);
4442: $key = &unescape($key);
4443: next if ($key =~ /^error: 2 /);
4444: $returnhash->{$key} = &thaw_unescape($value);
4445: }
4446: }
4447: }
4448: return;
4449: }
4450:
1.658 raeburn 4451: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4452:
4453: sub dcmailput {
1.685 raeburn 4454: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4455: my $status = &Apache::lonnet::critical(
1.740 www 4456: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4457: &escape($message),$server);
1.662 raeburn 4458: return $status;
4459: }
4460:
1.658 raeburn 4461: sub dcmaildump {
4462: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4463: my %returnhash=();
1.846 albertel 4464:
4465: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4466: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4467: &escape($enddate).':';
4468: my @esc_senders=map { &escape($_)} @$senders;
4469: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4470: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4471: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4472: if (($key) && ($value)) {
4473: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4474: }
4475: }
4476: }
4477: return %returnhash;
4478: }
1.662 raeburn 4479: # ---------------------------------------------------------- Domain roles
4480:
4481: sub get_domain_roles {
4482: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4483: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4484: $startdate = '.';
4485: }
1.1018 raeburn 4486: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4487: $enddate = '.';
4488: }
1.922 raeburn 4489: my $rolelist;
4490: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4491: $rolelist = join('&',@{$roles});
1.922 raeburn 4492: }
1.662 raeburn 4493: my %personnel = ();
1.841 albertel 4494:
4495: my %servers = &get_servers($dom,'library');
4496: foreach my $tryserver (keys(%servers)) {
4497: %{$personnel{$tryserver}}=();
4498: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4499: &escape($startdate).':'.
4500: &escape($enddate).':'.
4501: &escape($rolelist), $tryserver))) {
4502: my ($key,$value) = split(/\=/,$line,2);
4503: if (($key) && ($value)) {
4504: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4505: }
4506: }
1.662 raeburn 4507: }
4508: return %personnel;
4509: }
1.658 raeburn 4510:
1.1057 www 4511: # ----------------------------------------------------------- Interval timing
1.149 www 4512:
1.1153 www 4513: {
4514: # Caches needed for speedup of navmaps
4515: # We don't want to cache this for very long at all (5 seconds at most)
4516: #
4517: # The user for whom we cache
4518: my $cachedkey='';
4519: # The cached times for this user
4520: my %cachedtimes=();
4521: # When this was last done
1.1172.2.66 raeburn 4522: my $cachedtime='';
1.1153 www 4523:
4524: sub load_all_first_access {
1.1154 raeburn 4525: my ($uname,$udom)=@_;
1.1156 www 4526: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 4527: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4528: return;
4529: }
4530: $cachedtime=time;
4531: $cachedkey=$uname.':'.$udom;
4532: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4533: }
4534:
1.504 albertel 4535: sub get_first_access {
1.1162 raeburn 4536: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4537: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4538: if ($argsymb) { $symb=$argsymb; }
4539: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4540: if ($argmap) { $map = $argmap; }
1.926 albertel 4541: if ($type eq 'course') {
4542: $res='course';
4543: } elsif ($type eq 'map') {
1.588 albertel 4544: $res=&symbread($map);
4545: } else {
4546: $res=$symb;
4547: }
1.1153 www 4548: &load_all_first_access($uname,$udom);
4549: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4550: }
4551:
4552: sub set_first_access {
1.1162 raeburn 4553: my ($type,$interval)=@_;
1.790 albertel 4554: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4555: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4556: if ($type eq 'course') {
4557: $res='course';
4558: } elsif ($type eq 'map') {
1.588 albertel 4559: $res=&symbread($map);
4560: } else {
4561: $res=$symb;
4562: }
1.1153 www 4563: $cachedkey='';
1.1162 raeburn 4564: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4565: if (!$firstaccess) {
1.1162 raeburn 4566: my $start = time;
4567: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4568: $udom,$uname);
4569: if ($putres eq 'ok') {
4570: &put('timerinterval',{"$courseid\0$res"=>$interval},
4571: $udom,$uname);
4572: &appenv(
4573: {
4574: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4575: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4576: }
4577: );
4578: }
4579: return $putres;
1.505 albertel 4580: }
4581: return 'already_set';
1.504 albertel 4582: }
1.1153 www 4583: }
1.1172.2.32 raeburn 4584:
4585: sub checkout {
4586: my ($symb,$tuname,$tudom,$tcrsid)=@_;
4587: my $now=time;
4588: my $lonhost=$perlvar{'lonHostID'};
4589: my $infostr=&escape(
4590: 'CHECKOUTTOKEN&'.
4591: $tuname.'&'.
4592: $tudom.'&'.
4593: $tcrsid.'&'.
4594: $symb.'&'.
4595: $now.'&'.$ENV{'REMOTE_ADDR'});
4596: my $token=&reply('tmpput:'.$infostr,$lonhost);
4597: if ($token=~/^error\:/) {
4598: &logthis("<font color=\"blue\">WARNING: ".
4599: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
4600: "</font>");
4601: return '';
4602: }
4603:
4604: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
4605: $token=~tr/a-z/A-Z/;
4606:
4607: my %infohash=('resource.0.outtoken' => $token,
4608: 'resource.0.checkouttime' => $now,
4609: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
4610:
4611: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4612: return '';
4613: } else {
4614: &logthis("<font color=\"blue\">WARNING: ".
4615: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
4616: "</font>");
4617: }
4618:
4619: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4620: &escape('Checkout '.$infostr.' - '.
4621: $token)) ne 'ok') {
4622: return '';
4623: } else {
4624: &logthis("<font color=\"blue\">WARNING: ".
4625: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
4626: "</font>");
4627: }
4628: return $token;
4629: }
4630:
4631: # ------------------------------------------------------------ Check in an item
4632:
4633: sub checkin {
4634: my $token=shift;
4635: my $now=time;
4636: my ($ta,$tb,$lonhost)=split(/\*/,$token);
4637: $lonhost=~tr/A-Z/a-z/;
4638: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
4639: $dtoken=~s/\W/\_/g;
4640: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
4641: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
4642:
4643: unless (($tuname) && ($tudom)) {
4644: &logthis('Check in '.$token.' ('.$dtoken.') failed');
4645: return '';
4646: }
4647:
4648: unless (&allowed('mgr',$tcrsid)) {
4649: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
4650: $env{'user.name'}.' - '.$env{'user.domain'});
4651: return '';
4652: }
4653:
4654: my %infohash=('resource.0.intoken' => $token,
4655: 'resource.0.checkintime' => $now,
4656: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
4657:
4658: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4659: return '';
4660: }
4661:
4662: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4663: &escape('Checkin - '.$token)) ne 'ok') {
4664: return '';
4665: }
4666:
4667: return ($symb,$tuname,$tudom,$tcrsid);
4668: }
4669:
1.110 www 4670: # --------------------------------------------- Set Expire Date for Spreadsheet
4671:
4672: sub expirespread {
4673: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4674: my $cid=$env{'request.course.id'};
1.110 www 4675: if ($cid) {
4676: my $now=time;
4677: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4678: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4679: $env{'course.'.$cid.'.num'}.
1.110 www 4680: ':nohist_expirationdates:'.
4681: &escape($key).'='.$now,
1.620 albertel 4682: $env{'course.'.$cid.'.home'})
1.110 www 4683: }
4684: return 'ok';
1.14 www 4685: }
4686:
1.109 www 4687: # ----------------------------------------------------- Devalidate Spreadsheets
4688:
4689: sub devalidate {
1.325 www 4690: my ($symb,$uname,$udom)=@_;
1.620 albertel 4691: my $cid=$env{'request.course.id'};
1.109 www 4692: if ($cid) {
1.391 matthew 4693: # delete the stored spreadsheets for
4694: # - the student level sheet of this user in course's homespace
4695: # - the assessment level sheet for this resource
4696: # for this user in user's homespace
1.553 albertel 4697: # - current conditional state info
1.325 www 4698: my $key=$uname.':'.$udom.':';
1.109 www 4699: my $status=
1.299 matthew 4700: &del('nohist_calculatedsheets',
1.391 matthew 4701: [$key.'studentcalc:'],
1.620 albertel 4702: $env{'course.'.$cid.'.domain'},
4703: $env{'course.'.$cid.'.num'})
1.133 albertel 4704: .' '.
4705: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4706: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4707: unless ($status eq 'ok ok') {
4708: &logthis('Could not devalidate spreadsheet '.
1.325 www 4709: $uname.' at '.$udom.' for '.
1.109 www 4710: $symb.': '.$status);
1.133 albertel 4711: }
1.553 albertel 4712: &delenv('user.state.'.$cid);
1.109 www 4713: }
4714: }
4715:
1.265 albertel 4716: sub get_scalar {
4717: my ($string,$end) = @_;
4718: my $value;
4719: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4720: $value = $1;
4721: } elsif ($$string =~ s/^([^&]*?)&//) {
4722: $value = $1;
4723: }
4724: return &unescape($value);
4725: }
4726:
4727: sub array2str {
4728: my (@array) = @_;
4729: my $result=&arrayref2str(\@array);
4730: $result=~s/^__ARRAY_REF__//;
4731: $result=~s/__END_ARRAY_REF__$//;
4732: return $result;
4733: }
4734:
1.204 albertel 4735: sub arrayref2str {
4736: my ($arrayref) = @_;
1.265 albertel 4737: my $result='__ARRAY_REF__';
1.204 albertel 4738: foreach my $elem (@$arrayref) {
1.265 albertel 4739: if(ref($elem) eq 'ARRAY') {
4740: $result.=&arrayref2str($elem).'&';
4741: } elsif(ref($elem) eq 'HASH') {
4742: $result.=&hashref2str($elem).'&';
4743: } elsif(ref($elem)) {
4744: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4745: } else {
4746: $result.=&escape($elem).'&';
4747: }
4748: }
4749: $result=~s/\&$//;
1.265 albertel 4750: $result .= '__END_ARRAY_REF__';
1.204 albertel 4751: return $result;
4752: }
4753:
1.168 albertel 4754: sub hash2str {
1.204 albertel 4755: my (%hash) = @_;
4756: my $result=&hashref2str(\%hash);
1.265 albertel 4757: $result=~s/^__HASH_REF__//;
4758: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4759: return $result;
4760: }
4761:
4762: sub hashref2str {
4763: my ($hashref)=@_;
1.265 albertel 4764: my $result='__HASH_REF__';
1.800 albertel 4765: foreach my $key (sort(keys(%$hashref))) {
4766: if (ref($key) eq 'ARRAY') {
4767: $result.=&arrayref2str($key).'=';
4768: } elsif (ref($key) eq 'HASH') {
4769: $result.=&hashref2str($key).'=';
4770: } elsif (ref($key)) {
1.265 albertel 4771: $result.='=';
1.800 albertel 4772: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4773: } else {
1.1132 raeburn 4774: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4775: }
4776:
1.800 albertel 4777: if(ref($hashref->{$key}) eq 'ARRAY') {
4778: $result.=&arrayref2str($hashref->{$key}).'&';
4779: } elsif(ref($hashref->{$key}) eq 'HASH') {
4780: $result.=&hashref2str($hashref->{$key}).'&';
4781: } elsif(ref($hashref->{$key})) {
1.265 albertel 4782: $result.='&';
1.800 albertel 4783: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4784: } else {
1.800 albertel 4785: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4786: }
4787: }
1.168 albertel 4788: $result=~s/\&$//;
1.265 albertel 4789: $result .= '__END_HASH_REF__';
1.168 albertel 4790: return $result;
4791: }
4792:
4793: sub str2hash {
1.265 albertel 4794: my ($string)=@_;
4795: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4796: return %$hash;
4797: }
4798:
4799: sub str2hashref {
1.168 albertel 4800: my ($string) = @_;
1.265 albertel 4801:
4802: my %hash;
4803:
4804: if($string !~ /^__HASH_REF__/) {
4805: if (! ($string eq '' || !defined($string))) {
4806: $hash{'error'}='Not hash reference';
4807: }
4808: return (\%hash, $string);
4809: }
4810:
4811: $string =~ s/^__HASH_REF__//;
4812:
4813: while($string !~ /^__END_HASH_REF__/) {
4814: #key
4815: my $key='';
4816: if($string =~ /^__HASH_REF__/) {
4817: ($key, $string)=&str2hashref($string);
4818: if(defined($key->{'error'})) {
4819: $hash{'error'}='Bad data';
4820: return (\%hash, $string);
4821: }
4822: } elsif($string =~ /^__ARRAY_REF__/) {
4823: ($key, $string)=&str2arrayref($string);
4824: if($key->[0] eq 'Array reference error') {
4825: $hash{'error'}='Bad data';
4826: return (\%hash, $string);
4827: }
4828: } else {
4829: $string =~ s/^(.*?)=//;
1.267 albertel 4830: $key=&unescape($1);
1.265 albertel 4831: }
4832: $string =~ s/^=//;
4833:
4834: #value
4835: my $value='';
4836: if($string =~ /^__HASH_REF__/) {
4837: ($value, $string)=&str2hashref($string);
4838: if(defined($value->{'error'})) {
4839: $hash{'error'}='Bad data';
4840: return (\%hash, $string);
4841: }
4842: } elsif($string =~ /^__ARRAY_REF__/) {
4843: ($value, $string)=&str2arrayref($string);
4844: if($value->[0] eq 'Array reference error') {
4845: $hash{'error'}='Bad data';
4846: return (\%hash, $string);
4847: }
4848: } else {
4849: $value=&get_scalar(\$string,'__END_HASH_REF__');
4850: }
4851: $string =~ s/^&//;
4852:
4853: $hash{$key}=$value;
1.204 albertel 4854: }
1.265 albertel 4855:
4856: $string =~ s/^__END_HASH_REF__//;
4857:
4858: return (\%hash, $string);
1.204 albertel 4859: }
4860:
4861: sub str2array {
1.265 albertel 4862: my ($string)=@_;
4863: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4864: return @$array;
4865: }
4866:
4867: sub str2arrayref {
1.204 albertel 4868: my ($string) = @_;
1.265 albertel 4869: my @array;
4870:
4871: if($string !~ /^__ARRAY_REF__/) {
4872: if (! ($string eq '' || !defined($string))) {
4873: $array[0]='Array reference error';
4874: }
4875: return (\@array, $string);
4876: }
4877:
4878: $string =~ s/^__ARRAY_REF__//;
4879:
4880: while($string !~ /^__END_ARRAY_REF__/) {
4881: my $value='';
4882: if($string =~ /^__HASH_REF__/) {
4883: ($value, $string)=&str2hashref($string);
4884: if(defined($value->{'error'})) {
4885: $array[0] ='Array reference error';
4886: return (\@array, $string);
4887: }
4888: } elsif($string =~ /^__ARRAY_REF__/) {
4889: ($value, $string)=&str2arrayref($string);
4890: if($value->[0] eq 'Array reference error') {
4891: $array[0] ='Array reference error';
4892: return (\@array, $string);
4893: }
4894: } else {
4895: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4896: }
4897: $string =~ s/^&//;
4898:
4899: push(@array, $value);
1.191 harris41 4900: }
1.265 albertel 4901:
4902: $string =~ s/^__END_ARRAY_REF__//;
4903:
4904: return (\@array, $string);
1.168 albertel 4905: }
4906:
1.167 albertel 4907: # -------------------------------------------------------------------Temp Store
4908:
1.168 albertel 4909: sub tmpreset {
4910: my ($symb,$namespace,$domain,$stuname) = @_;
4911: if (!$symb) {
4912: $symb=&symbread();
1.620 albertel 4913: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4914: }
4915: $symb=escape($symb);
4916:
1.620 albertel 4917: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4918: $namespace=~s/\//\_/g;
4919: $namespace=~s/\W//g;
4920:
1.620 albertel 4921: if (!$domain) { $domain=$env{'user.domain'}; }
4922: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4923: if ($domain eq 'public' && $stuname eq 'public') {
4924: $stuname=$ENV{'REMOTE_ADDR'};
4925: }
1.1117 foxr 4926: my $path=LONCAPA::tempdir();
1.168 albertel 4927: my %hash;
4928: if (tie(%hash,'GDBM_File',
4929: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4930: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4931: foreach my $key (keys(%hash)) {
1.180 albertel 4932: if ($key=~ /:$symb/) {
1.168 albertel 4933: delete($hash{$key});
4934: }
4935: }
4936: }
4937: }
4938:
1.167 albertel 4939: sub tmpstore {
1.168 albertel 4940: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4941:
4942: if (!$symb) {
4943: $symb=&symbread();
1.620 albertel 4944: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4945: }
4946: $symb=escape($symb);
4947:
4948: if (!$namespace) {
4949: # I don't think we would ever want to store this for a course.
4950: # it seems this will only be used if we don't have a course.
1.620 albertel 4951: #$namespace=$env{'request.course.id'};
1.168 albertel 4952: #if (!$namespace) {
1.620 albertel 4953: $namespace=$env{'request.state'};
1.168 albertel 4954: #}
4955: }
4956: $namespace=~s/\//\_/g;
4957: $namespace=~s/\W//g;
1.620 albertel 4958: if (!$domain) { $domain=$env{'user.domain'}; }
4959: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4960: if ($domain eq 'public' && $stuname eq 'public') {
4961: $stuname=$ENV{'REMOTE_ADDR'};
4962: }
1.168 albertel 4963: my $now=time;
4964: my %hash;
1.1117 foxr 4965: my $path=LONCAPA::tempdir();
1.168 albertel 4966: if (tie(%hash,'GDBM_File',
4967: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4968: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4969: $hash{"version:$symb"}++;
4970: my $version=$hash{"version:$symb"};
4971: my $allkeys='';
4972: foreach my $key (keys(%$storehash)) {
4973: $allkeys.=$key.':';
1.591 albertel 4974: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4975: }
4976: $hash{"$version:$symb:timestamp"}=$now;
4977: $allkeys.='timestamp';
4978: $hash{"$version:keys:$symb"}=$allkeys;
4979: if (untie(%hash)) {
4980: return 'ok';
4981: } else {
4982: return "error:$!";
4983: }
4984: } else {
4985: return "error:$!";
4986: }
4987: }
1.167 albertel 4988:
1.168 albertel 4989: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4990:
1.168 albertel 4991: sub tmprestore {
4992: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4993:
1.168 albertel 4994: if (!$symb) {
4995: $symb=&symbread();
1.620 albertel 4996: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4997: }
4998: $symb=escape($symb);
4999:
1.620 albertel 5000: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5001:
1.620 albertel 5002: if (!$domain) { $domain=$env{'user.domain'}; }
5003: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5004: if ($domain eq 'public' && $stuname eq 'public') {
5005: $stuname=$ENV{'REMOTE_ADDR'};
5006: }
1.168 albertel 5007: my %returnhash;
5008: $namespace=~s/\//\_/g;
5009: $namespace=~s/\W//g;
5010: my %hash;
1.1117 foxr 5011: my $path=LONCAPA::tempdir();
1.168 albertel 5012: if (tie(%hash,'GDBM_File',
5013: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5014: &GDBM_READER(),0640)) {
1.168 albertel 5015: my $version=$hash{"version:$symb"};
5016: $returnhash{'version'}=$version;
5017: my $scope;
5018: for ($scope=1;$scope<=$version;$scope++) {
5019: my $vkeys=$hash{"$scope:keys:$symb"};
5020: my @keys=split(/:/,$vkeys);
5021: my $key;
5022: $returnhash{"$scope:keys"}=$vkeys;
5023: foreach $key (@keys) {
1.591 albertel 5024: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5025: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5026: }
5027: }
1.168 albertel 5028: if (!(untie(%hash))) {
5029: return "error:$!";
5030: }
5031: } else {
5032: return "error:$!";
5033: }
5034: return %returnhash;
1.167 albertel 5035: }
5036:
1.9 www 5037: # ----------------------------------------------------------------------- Store
5038:
5039: sub store {
1.1172.2.64 raeburn 5040: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5041: my $home='';
5042:
1.168 albertel 5043: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5044:
1.213 www 5045: $symb=&symbclean($symb);
1.122 albertel 5046: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5047:
1.620 albertel 5048: if (!$domain) { $domain=$env{'user.domain'}; }
5049: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5050:
5051: &devalidate($symb,$stuname,$domain);
1.109 www 5052:
5053: $symb=escape($symb);
1.187 www 5054: if (!$namespace) {
1.620 albertel 5055: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5056: return '';
5057: }
5058: }
1.620 albertel 5059: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5060:
5061: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5062: $$storehash{'host'}=$perlvar{'lonHostID'};
5063:
1.12 www 5064: my $namevalue='';
1.800 albertel 5065: foreach my $key (keys(%$storehash)) {
5066: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5067: }
1.12 www 5068: $namevalue=~s/\&$//;
1.187 www 5069: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 5070: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5071: }
5072:
1.47 www 5073: # -------------------------------------------------------------- Critical Store
5074:
5075: sub cstore {
1.1172.2.64 raeburn 5076: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5077: my $home='';
5078:
1.168 albertel 5079: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5080:
1.213 www 5081: $symb=&symbclean($symb);
1.122 albertel 5082: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5083:
1.620 albertel 5084: if (!$domain) { $domain=$env{'user.domain'}; }
5085: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5086:
5087: &devalidate($symb,$stuname,$domain);
1.109 www 5088:
5089: $symb=escape($symb);
1.187 www 5090: if (!$namespace) {
1.620 albertel 5091: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5092: return '';
5093: }
5094: }
1.620 albertel 5095: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5096:
5097: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5098: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5099:
1.47 www 5100: my $namevalue='';
1.800 albertel 5101: foreach my $key (keys(%$storehash)) {
5102: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5103: }
1.47 www 5104: $namevalue=~s/\&$//;
1.187 www 5105: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5106: return critical
1.1172.2.64 raeburn 5107: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5108: }
5109:
1.9 www 5110: # --------------------------------------------------------------------- Restore
5111:
5112: sub restore {
1.124 www 5113: my ($symb,$namespace,$domain,$stuname) = @_;
5114: my $home='';
5115:
1.168 albertel 5116: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5117:
1.122 albertel 5118: if (!$symb) {
1.1172.2.26 raeburn 5119: return if ($namespace eq 'courserequests');
5120: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5121: } else {
1.1172.2.26 raeburn 5122: unless ($namespace eq 'courserequests') {
5123: $symb=&escape(&symbclean($symb));
5124: }
1.122 albertel 5125: }
1.188 www 5126: if (!$namespace) {
1.620 albertel 5127: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5128: return '';
5129: }
5130: }
1.620 albertel 5131: if (!$domain) { $domain=$env{'user.domain'}; }
5132: if (!$stuname) { $stuname=$env{'user.name'}; }
5133: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5134: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5135:
1.12 www 5136: my %returnhash=();
1.800 albertel 5137: foreach my $line (split(/\&/,$answer)) {
5138: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5139: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5140: }
1.75 www 5141: my $version;
5142: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5143: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5144: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5145: }
1.75 www 5146: }
1.13 www 5147: return %returnhash;
1.34 www 5148: }
5149:
5150: # ---------------------------------------------------------- Course Description
1.1118 foxr 5151: #
5152: #
1.34 www 5153:
5154: sub coursedescription {
1.731 albertel 5155: my ($courseid,$args)=@_;
1.34 www 5156: $courseid=~s/^\///;
1.49 www 5157: $courseid=~s/\_/\//g;
1.34 www 5158: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5159: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5160: my $normalid=$cdomain.'_'.$cnum;
5161: # need to always cache even if we get errors otherwise we keep
5162: # trying and trying and trying to get the course description.
5163: my %envhash=();
5164: my %returnhash=();
1.731 albertel 5165:
5166: my $expiretime=600;
5167: if ($env{'request.course.id'} eq $normalid) {
5168: $expiretime=120;
5169: }
5170:
5171: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5172: if (!$args->{'freshen_cache'}
5173: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5174: foreach my $key (keys(%env)) {
5175: next if ($key !~ /^\Q$prefix\E(.*)/);
5176: my ($setting) = $1;
5177: $returnhash{$setting} = $env{$key};
5178: }
5179: return %returnhash;
5180: }
5181:
1.1118 foxr 5182: # get the data again
5183:
1.731 albertel 5184: if (!$args->{'one_time'}) {
5185: $envhash{'course.'.$normalid.'.last_cache'}=time;
5186: }
1.811 albertel 5187:
1.34 www 5188: if ($chome ne 'no_host') {
1.302 albertel 5189: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5190: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5191: my $username = $env{'user.name'}; # Defult username
5192: if(defined $args->{'user'}) {
5193: $username = $args->{'user'};
5194: }
1.129 albertel 5195: $returnhash{'home'}= $chome;
5196: $returnhash{'domain'} = $cdomain;
5197: $returnhash{'num'} = $cnum;
1.741 raeburn 5198: if (!defined($returnhash{'type'})) {
5199: $returnhash{'type'} = 'Course';
5200: }
1.130 albertel 5201: while (my ($name,$value) = each %returnhash) {
1.53 www 5202: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5203: }
1.270 www 5204: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5205: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5206: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5207: $envhash{'course.'.$normalid.'.home'}=$chome;
5208: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5209: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5210: }
5211: }
1.731 albertel 5212: if (!$args->{'one_time'}) {
1.949 raeburn 5213: &appenv(\%envhash);
1.731 albertel 5214: }
1.302 albertel 5215: return %returnhash;
1.461 www 5216: }
5217:
1.1080 raeburn 5218: sub update_released_required {
5219: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5220: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5221: $cid = $env{'request.course.id'};
5222: $cdom = $env{'course.'.$cid.'.domain'};
5223: $cnum = $env{'course.'.$cid.'.num'};
5224: $chome = $env{'course.'.$cid.'.home'};
5225: }
5226: if ($needsrelease) {
5227: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5228: my $needsupdate;
5229: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5230: $needsupdate = 1;
5231: } else {
5232: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5233: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5234: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5235: $needsupdate = 1;
5236: }
5237: }
5238: if ($needsupdate) {
5239: my %needshash = (
5240: 'internal.releaserequired' => $needsrelease,
5241: );
5242: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5243: if ($putresult eq 'ok') {
5244: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5245: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5246: if (ref($crsinfo{$cid}) eq 'HASH') {
5247: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5248: &courseidput($cdom,\%crsinfo,$chome,'notime');
5249: }
5250: }
5251: }
5252: }
5253: return;
5254: }
5255:
1.461 www 5256: # -------------------------------------------------See if a user is privileged
5257:
5258: sub privileged {
1.1172.2.23 raeburn 5259: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5260: my $now = time;
1.1172.2.23 raeburn 5261: my $roles;
5262: if (ref($possroles) eq 'ARRAY') {
5263: $roles = $possroles;
5264: } else {
5265: $roles = ['dc','su'];
5266: }
5267: if (ref($possdomains) eq 'ARRAY') {
5268: my %privileged = &privileged_by_domain($possdomains,$roles);
5269: foreach my $dom (@{$possdomains}) {
5270: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5271: (ref($privileged{$dom}) eq 'HASH')) {
5272: foreach my $role (@{$roles}) {
5273: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5274: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5275: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5276: return 1 unless (($end && $end < $now) ||
5277: ($start && $start > $now));
5278: }
5279: }
5280: }
5281: }
5282: }
5283: } else {
5284: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5285: my $now = time;
1.1170 droeschl 5286:
1.1172.2.58 raeburn 5287: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5288: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5289: if (grep(/^\Q$trole\E$/,@{$roles})) {
5290: return 1 unless ($tend && $tend < $now)
5291: or ($tstart && $tstart > $now);
1.1170 droeschl 5292: }
1.1172.2.23 raeburn 5293: }
5294: }
1.461 www 5295: return 0;
1.9 www 5296: }
1.1 albertel 5297:
1.1172.2.23 raeburn 5298: sub privileged_by_domain {
5299: my ($domains,$roles) = @_;
5300: my %privileged = ();
5301: my $cachetime = 60*60*24;
5302: my $now = time;
5303: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5304: return %privileged;
5305: }
5306: foreach my $dom (@{$domains}) {
5307: next if (ref($privileged{$dom}) eq 'HASH');
5308: my $needroles;
5309: foreach my $role (@{$roles}) {
5310: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5311: if (defined($cached)) {
5312: if (ref($result) eq 'HASH') {
5313: $privileged{$dom}{$role} = $result;
5314: }
5315: } else {
5316: $needroles = 1;
5317: }
5318: }
5319: if ($needroles) {
5320: my %dompersonnel = &get_domain_roles($dom,$roles);
5321: $privileged{$dom} = {};
5322: foreach my $server (keys(%dompersonnel)) {
5323: if (ref($dompersonnel{$server}) eq 'HASH') {
5324: foreach my $item (keys(%{$dompersonnel{$server}})) {
5325: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5326: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5327: next if ($end && $end < $now);
5328: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5329: $dompersonnel{$server}{$item};
5330: }
5331: }
5332: }
5333: if (ref($privileged{$dom}) eq 'HASH') {
5334: foreach my $role (@{$roles}) {
5335: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5336: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5337: } else {
5338: my %hash = ();
5339: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5340: }
5341: }
5342: }
5343: }
5344: }
5345: return %privileged;
5346: }
5347:
1.103 harris41 5348: # -------------------------------------------------------- Get user privileges
1.11 www 5349:
5350: sub rolesinit {
1.1169 droeschl 5351: my ($domain, $username) = @_;
5352: my %userroles = ('user.login.time' => time);
5353: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5354:
5355: # firstaccess and timerinterval are related to timed maps/resources.
5356: # also, blocking can be triggered by an activating timer
5357: # it's saved in the user's %env.
5358: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5359: my %timerinterval = &dump('timerinterval', $domain, $username);
5360: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5361: %timerintchk, %timerintenv);
5362:
1.1162 raeburn 5363: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5364: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5365: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5366: }
1.1169 droeschl 5367:
1.1162 raeburn 5368: foreach my $key (keys(%timerinterval)) {
5369: my ($cid,$rest) = split(/\0/,$key);
5370: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5371: }
1.1169 droeschl 5372:
1.11 www 5373: my %allroles=();
1.1162 raeburn 5374: my %allgroups=();
1.11 www 5375:
1.1172.2.58 raeburn 5376: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5377: my $role = $rolesdump{$area};
5378: $area =~ s/\_\w\w$//;
5379:
5380: my ($trole, $tend, $tstart, $group_privs);
5381:
5382: if ($role =~ /^cr/) {
5383: # Custom role, defined by a user
5384: # e.g., user.role.cr/msu/smith/mynewrole
5385: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5386: $trole = $1;
5387: ($tend, $tstart) = split('_', $2);
5388: } else {
5389: $trole = $role;
5390: }
5391: } elsif ($role =~ m|^gr/|) {
5392: # Role of member in a group, defined within a course/community
5393: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5394: ($trole, $tend, $tstart) = split(/_/, $role);
5395: next if $tstart eq '-1';
5396: ($trole, $group_privs) = split(/\//, $trole);
5397: $group_privs = &unescape($group_privs);
5398: } else {
5399: # Just a normal role, defined in roles.tab
5400: ($trole, $tend, $tstart) = split(/_/,$role);
5401: }
5402:
5403: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5404: $username);
5405: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5406:
5407: # role expired or not available yet?
5408: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5409: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5410:
5411: next if $area eq '' or $trole eq '';
5412:
5413: my $spec = "$trole.$area";
5414: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5415:
5416: if ($trole =~ /^cr\//) {
5417: # Custom role, defined by a user
5418: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5419: } elsif ($trole eq 'gr') {
5420: # Role of a member in a group, defined within a course/community
5421: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5422: next;
5423: } else {
5424: # Normal role, defined in roles.tab
5425: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5426: }
5427:
5428: my $cid = $tdomain.'_'.$trest;
5429: unless ($firstaccchk{$cid}) {
5430: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5431: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5432: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5433: $coursetimerstarts{$cid}{$item};
5434: }
5435: }
5436: $firstaccchk{$cid} = 1;
5437: }
5438: unless ($timerintchk{$cid}) {
5439: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5440: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5441: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5442: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5443: }
1.12 www 5444: }
1.1169 droeschl 5445: $timerintchk{$cid} = 1;
1.191 harris41 5446: }
1.11 www 5447: }
1.1169 droeschl 5448:
5449: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5450: \%allroles, \%allgroups);
5451: $env{'user.adv'} = $userroles{'user.adv'};
5452:
1.1162 raeburn 5453: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5454: }
5455:
1.567 raeburn 5456: sub set_arearole {
1.1172.2.19 raeburn 5457: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5458: unless ($nolog) {
1.567 raeburn 5459: # log the associated role with the area
1.1172.2.19 raeburn 5460: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5461: }
1.743 albertel 5462: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5463: }
5464:
5465: sub custom_roleprivs {
5466: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5467: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 5468: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5469: if (&hostname($homsvr) ne '') {
1.567 raeburn 5470: my ($rdummy,$roledef)=
5471: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5472: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5473: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5474: if (defined($syspriv)) {
1.1043 raeburn 5475: if ($trest =~ /^$match_community$/) {
5476: $syspriv =~ s/bre\&S//;
5477: }
1.567 raeburn 5478: $$allroles{'cm./'}.=':'.$syspriv;
5479: $$allroles{$spec.'./'}.=':'.$syspriv;
5480: }
5481: if ($tdomain ne '') {
5482: if (defined($dompriv)) {
5483: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5484: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5485: }
5486: if (($trest ne '') && (defined($coursepriv))) {
5487: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5488: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5489: }
5490: }
5491: }
5492: }
5493: }
5494:
1.678 raeburn 5495: sub group_roleprivs {
5496: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5497: my $access = 1;
5498: my $now = time;
5499: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5500: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5501: if ($access) {
1.811 albertel 5502: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5503: $$allgroups{$course}{$group} .=':'.$group_privs;
5504: }
5505: }
1.567 raeburn 5506:
5507: sub standard_roleprivs {
5508: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5509: if (defined($pr{$trole.':s'})) {
5510: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5511: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5512: }
5513: if ($tdomain ne '') {
5514: if (defined($pr{$trole.':d'})) {
5515: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5516: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5517: }
5518: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5519: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5520: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5521: }
5522: }
5523: }
5524:
5525: sub set_userprivs {
1.1064 raeburn 5526: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5527: my $author=0;
5528: my $adv=0;
1.678 raeburn 5529: my %grouproles = ();
5530: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5531: my @groupkeys;
1.1000 raeburn 5532: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5533: push(@groupkeys,$role);
5534: }
5535: if (ref($groups_roles) eq 'HASH') {
5536: foreach my $key (keys(%{$groups_roles})) {
5537: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5538: push(@groupkeys,$key);
5539: }
5540: }
5541: }
5542: if (@groupkeys > 0) {
5543: foreach my $role (@groupkeys) {
5544: my ($trole,$area,$sec,$extendedarea);
5545: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5546: $trole = $1;
5547: $area = $2;
5548: $sec = $3;
5549: $extendedarea = $area.$sec;
5550: if (exists($$allgroups{$area})) {
5551: foreach my $group (keys(%{$$allgroups{$area}})) {
5552: my $spec = $trole.'.'.$extendedarea;
5553: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5554: $$allgroups{$area}{$group};
1.1064 raeburn 5555: }
1.678 raeburn 5556: }
5557: }
5558: }
5559: }
5560: }
1.800 albertel 5561: foreach my $group (keys(%grouproles)) {
5562: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5563: }
1.800 albertel 5564: foreach my $role (keys(%{$allroles})) {
5565: my %thesepriv;
1.941 raeburn 5566: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5567: foreach my $item (split(/:/,$$allroles{$role})) {
5568: if ($item ne '') {
5569: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5570: if ($restrictions eq '') {
5571: $thesepriv{$privilege}='F';
5572: } elsif ($thesepriv{$privilege} ne 'F') {
5573: $thesepriv{$privilege}.=$restrictions;
5574: }
5575: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5576: }
5577: }
5578: my $thesestr='';
1.1104 raeburn 5579: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5580: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5581: }
5582: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5583: }
5584: return ($author,$adv);
5585: }
5586:
1.994 raeburn 5587: sub role_status {
1.1104 raeburn 5588: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5589: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 5590: my ($one,$two) = split(m{\./},$rolekey,2);
5591: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5592: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 5593: $$where = '/'.$two;
1.994 raeburn 5594: $$trolecode=$$role.'.'.$$where;
5595: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5596: $$tstatus='is';
1.1104 raeburn 5597: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5598: $$tstatus='future';
1.1034 raeburn 5599: if ($$tstart<$now) {
5600: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5601: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5602: my (%allroles,%allgroups,$group_privs,
5603: %groups_roles,@rolecodes);
1.1002 raeburn 5604: my %userroles = (
5605: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5606: );
1.1064 raeburn 5607: @rolecodes = ('cm');
1.1002 raeburn 5608: my $spec=$$role.'.'.$$where;
5609: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5610: if ($$role =~ /^cr\//) {
5611: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5612: push(@rolecodes,'cr');
1.1002 raeburn 5613: } elsif ($$role eq 'gr') {
1.1064 raeburn 5614: push(@rolecodes,$$role);
1.1002 raeburn 5615: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5616: $env{'user.name'});
1.1064 raeburn 5617: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5618: (undef,my $group_privs) = split(/\//,$trole);
5619: $group_privs = &unescape($group_privs);
5620: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5621: 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 5622: &get_groups_roles($tdomain,$trest,
5623: \%course_roles,\@rolecodes,
5624: \%groups_roles);
1.1002 raeburn 5625: } else {
1.1064 raeburn 5626: push(@rolecodes,$$role);
1.1002 raeburn 5627: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5628: }
1.1064 raeburn 5629: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5630: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5631: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5632: }
5633: }
1.1034 raeburn 5634: $$tstatus = 'is';
1.1002 raeburn 5635: }
1.994 raeburn 5636: }
5637: if ($$tend) {
1.1104 raeburn 5638: if ($$tend<$update) {
1.994 raeburn 5639: $$tstatus='expired';
5640: } elsif ($$tend<$now) {
5641: $$tstatus='will_not';
5642: }
5643: }
5644: }
5645: }
5646: }
5647:
1.1104 raeburn 5648: sub get_groups_roles {
5649: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5650: return unless((ref($cdom_courseroles) eq 'HASH') &&
5651: (ref($rolecodes) eq 'ARRAY') &&
5652: (ref($groups_roles) eq 'HASH'));
5653: if (keys(%{$cdom_courseroles}) > 0) {
5654: my ($cnum) = ($rest =~ /^($match_courseid)/);
5655: if ($cdom ne '' && $cnum ne '') {
5656: foreach my $key (keys(%{$cdom_courseroles})) {
5657: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5658: my $crsrole = $1;
5659: my $crssec = $2;
5660: if ($crsrole =~ /^cr/) {
5661: unless (grep(/^cr$/,@{$rolecodes})) {
5662: push(@{$rolecodes},'cr');
5663: }
5664: } else {
5665: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5666: push(@{$rolecodes},$crsrole);
5667: }
5668: }
5669: my $rolekey = "$crsrole./$cdom/$cnum";
5670: if ($crssec ne '') {
5671: $rolekey .= "/$crssec";
5672: }
5673: $rolekey .= './';
5674: $groups_roles->{$rolekey} = $rolecodes;
5675: }
5676: }
5677: }
5678: }
5679: return;
5680: }
5681:
5682: sub delete_env_groupprivs {
5683: my ($where,$courseroles,$possroles) = @_;
5684: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5685: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5686: unless (ref($courseroles->{$udom}) eq 'HASH') {
5687: %{$courseroles->{$udom}} =
5688: &get_my_roles('','','userroles',['active'],
5689: $possroles,[$udom],1);
5690: }
5691: if (ref($courseroles->{$udom}) eq 'HASH') {
5692: foreach my $item (keys(%{$courseroles->{$udom}})) {
5693: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5694: my $area = '/'.$cdom.'/'.$cnum;
5695: my $privkey = "user.priv.$crsrole.$area";
5696: if ($crssec ne '') {
5697: $privkey .= '/'.$crssec;
5698: }
5699: $privkey .= ".$area/$group";
5700: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5701: }
5702: }
5703: return;
5704: }
5705:
1.994 raeburn 5706: sub check_adhoc_privs {
1.1104 raeburn 5707: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5708: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9 raeburn 5709: my $setprivs;
1.994 raeburn 5710: if ($env{$cckey}) {
5711: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5712: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5713: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5714: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5715: $setprivs = 1;
1.994 raeburn 5716: }
5717: } else {
1.1088 raeburn 5718: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5719: $setprivs = 1;
1.994 raeburn 5720: }
1.1172.2.9 raeburn 5721: return $setprivs;
1.994 raeburn 5722: }
5723:
5724: sub set_adhoc_privileges {
5725: # role can be cc or ca
1.1088 raeburn 5726: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5727: my $area = '/'.$dcdom.'/'.$pickedcourse;
5728: my $spec = $role.'.'.$area;
5729: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 5730: $env{'user.name'},1);
1.994 raeburn 5731: my %ccrole = ();
5732: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5733: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5734: &appenv(\%userroles,[$role,'cm']);
5735: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5736: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5737: &appenv( {'request.role' => $spec,
5738: 'request.role.domain' => $dcdom,
5739: 'request.course.sec' => ''
5740: }
5741: );
5742: my $tadv=0;
5743: if (&allowed('adv') eq 'F') { $tadv=1; }
5744: &appenv({'request.role.adv' => $tadv});
5745: }
1.994 raeburn 5746: }
5747:
1.12 www 5748: # --------------------------------------------------------------- get interface
5749:
5750: sub get {
1.131 albertel 5751: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5752: my $items='';
1.800 albertel 5753: foreach my $item (@$storearr) {
5754: $items.=&escape($item).'&';
1.191 harris41 5755: }
1.12 www 5756: $items=~s/\&$//;
1.620 albertel 5757: if (!$udomain) { $udomain=$env{'user.domain'}; }
5758: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5759: my $uhome=&homeserver($uname,$udomain);
5760:
1.133 albertel 5761: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5762: my @pairs=split(/\&/,$rep);
1.273 albertel 5763: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5764: return @pairs;
5765: }
1.15 www 5766: my %returnhash=();
1.42 www 5767: my $i=0;
1.800 albertel 5768: foreach my $item (@$storearr) {
5769: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5770: $i++;
1.191 harris41 5771: }
1.15 www 5772: return %returnhash;
1.27 www 5773: }
5774:
5775: # --------------------------------------------------------------- del interface
5776:
5777: sub del {
1.133 albertel 5778: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5779: my $items='';
1.800 albertel 5780: foreach my $item (@$storearr) {
5781: $items.=&escape($item).'&';
1.191 harris41 5782: }
1.984 neumanie 5783:
1.27 www 5784: $items=~s/\&$//;
1.620 albertel 5785: if (!$udomain) { $udomain=$env{'user.domain'}; }
5786: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5787: my $uhome=&homeserver($uname,$udomain);
5788: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5789: }
5790:
5791: # -------------------------------------------------------------- dump interface
5792:
1.1172.2.22 raeburn 5793: sub unserialize {
5794: my ($rep, $escapedkeys) = @_;
5795:
5796: return {} if $rep =~ /^error/;
5797:
5798: my %returnhash=();
5799: foreach my $item (split(/\&/,$rep)) {
5800: my ($key, $value) = split(/=/, $item, 2);
5801: $key = unescape($key) unless $escapedkeys;
5802: next if $key =~ /^error: 2 /;
5803: $returnhash{$key} = &thaw_unescape($value);
5804: }
5805: return \%returnhash;
5806: }
5807:
5808: # see Lond::dump_with_regexp
5809: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5810: sub dump {
1.1172.2.22 raeburn 5811: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5812: if (!$udomain) { $udomain=$env{'user.domain'}; }
5813: if (!$uname) { $uname=$env{'user.name'}; }
5814: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5815:
1.1172.2.55 raeburn 5816: if ($regexp) {
5817: $regexp=&escape($regexp);
5818: } else {
5819: $regexp='.';
5820: }
1.1172.2.22 raeburn 5821: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
5822: # user is hosted on this machine
1.1172.2.55 raeburn 5823: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 5824: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 5825: return %{&unserialize($reply, $escapedkeys)};
5826: }
1.1166 raeburn 5827: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5828: my @pairs=split(/\&/,$rep);
5829: my %returnhash=();
1.1098 foxr 5830: if (!($rep =~ /^error/ )) {
5831: foreach my $item (@pairs) {
5832: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 5833: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 5834: next if ($key =~ /^error: 2 /);
5835: $returnhash{$key}=&thaw_unescape($value);
5836: }
1.755 albertel 5837: }
5838: return %returnhash;
1.407 www 5839: }
5840:
1.1098 foxr 5841:
1.717 albertel 5842: # --------------------------------------------------------- dumpstore interface
5843:
5844: sub dumpstore {
5845: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 5846: # same as dump but keys must be escaped. They may contain colon separated
5847: # lists of values that may themself contain colons (e.g. symbs).
5848: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5849: }
5850:
1.407 www 5851: # -------------------------------------------------------------- keys interface
5852:
5853: sub getkeys {
5854: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5855: if (!$udomain) { $udomain=$env{'user.domain'}; }
5856: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5857: my $uhome=&homeserver($uname,$udomain);
5858: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5859: my @keyarray=();
1.800 albertel 5860: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5861: next if ($key =~ /^error: 2 /);
1.800 albertel 5862: push(@keyarray,&unescape($key));
1.407 www 5863: }
5864: return @keyarray;
1.318 matthew 5865: }
5866:
1.319 matthew 5867: # --------------------------------------------------------------- currentdump
5868: sub currentdump {
1.328 matthew 5869: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5870: $courseid = $env{'request.course.id'} if (! defined($courseid));
5871: $sdom = $env{'user.domain'} if (! defined($sdom));
5872: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5873: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 5874: my $rep;
5875:
5876: if (grep { $_ eq $uhome } current_machine_ids()) {
5877: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5878: $courseid)));
5879: } else {
5880: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5881: }
5882:
1.318 matthew 5883: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5884: #
1.318 matthew 5885: my %returnhash=();
1.319 matthew 5886: #
5887: if ($rep eq "unknown_cmd") {
5888: # an old lond will not know currentdump
5889: # Do a dump and make it look like a currentdump
1.822 albertel 5890: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5891: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5892: my %hash = @tmp;
5893: @tmp=();
1.424 matthew 5894: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5895: } else {
5896: my @pairs=split(/\&/,$rep);
1.800 albertel 5897: foreach my $pair (@pairs) {
5898: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5899: my ($symb,$param) = split(/:/,$key);
5900: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5901: &thaw_unescape($value);
1.319 matthew 5902: }
1.191 harris41 5903: }
1.12 www 5904: return %returnhash;
1.424 matthew 5905: }
5906:
5907: sub convert_dump_to_currentdump{
5908: my %hash = %{shift()};
5909: my %returnhash;
5910: # Code ripped from lond, essentially. The only difference
5911: # here is the unescaping done by lonnet::dump(). Conceivably
5912: # we might run in to problems with parameter names =~ /^v\./
5913: while (my ($key,$value) = each(%hash)) {
5914: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5915: $symb = &unescape($symb);
5916: $param = &unescape($param);
1.424 matthew 5917: next if ($v eq 'version' || $symb eq 'keys');
5918: next if (exists($returnhash{$symb}) &&
5919: exists($returnhash{$symb}->{$param}) &&
5920: $returnhash{$symb}->{'v.'.$param} > $v);
5921: $returnhash{$symb}->{$param}=$value;
5922: $returnhash{$symb}->{'v.'.$param}=$v;
5923: }
5924: #
5925: # Remove all of the keys in the hashes which keep track of
5926: # the version of the parameter.
5927: while (my ($symb,$param_hash) = each(%returnhash)) {
5928: # use a foreach because we are going to delete from the hash.
5929: foreach my $key (keys(%$param_hash)) {
5930: delete($param_hash->{$key}) if ($key =~ /^v\./);
5931: }
5932: }
5933: return \%returnhash;
1.12 www 5934: }
5935:
1.627 albertel 5936: # ------------------------------------------------------ critical inc interface
5937:
5938: sub cinc {
5939: return &inc(@_,'critical');
5940: }
5941:
1.449 matthew 5942: # --------------------------------------------------------------- inc interface
5943:
5944: sub inc {
1.627 albertel 5945: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5946: if (!$udomain) { $udomain=$env{'user.domain'}; }
5947: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5948: my $uhome=&homeserver($uname,$udomain);
5949: my $items='';
5950: if (! ref($store)) {
5951: # got a single value, so use that instead
5952: $items = &escape($store).'=&';
5953: } elsif (ref($store) eq 'SCALAR') {
5954: $items = &escape($$store).'=&';
5955: } elsif (ref($store) eq 'ARRAY') {
5956: $items = join('=&',map {&escape($_);} @{$store});
5957: } elsif (ref($store) eq 'HASH') {
5958: while (my($key,$value) = each(%{$store})) {
5959: $items.= &escape($key).'='.&escape($value).'&';
5960: }
5961: }
5962: $items=~s/\&$//;
1.627 albertel 5963: if ($critical) {
5964: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5965: } else {
5966: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5967: }
1.449 matthew 5968: }
5969:
1.12 www 5970: # --------------------------------------------------------------- put interface
5971:
5972: sub put {
1.134 albertel 5973: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5974: if (!$udomain) { $udomain=$env{'user.domain'}; }
5975: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5976: my $uhome=&homeserver($uname,$udomain);
1.12 www 5977: my $items='';
1.800 albertel 5978: foreach my $item (keys(%$storehash)) {
5979: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5980: }
1.12 www 5981: $items=~s/\&$//;
1.134 albertel 5982: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5983: }
5984:
1.631 albertel 5985: # ------------------------------------------------------------ newput interface
5986:
5987: sub newput {
5988: my ($namespace,$storehash,$udomain,$uname)=@_;
5989: if (!$udomain) { $udomain=$env{'user.domain'}; }
5990: if (!$uname) { $uname=$env{'user.name'}; }
5991: my $uhome=&homeserver($uname,$udomain);
5992: my $items='';
5993: foreach my $key (keys(%$storehash)) {
5994: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5995: }
5996: $items=~s/\&$//;
5997: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5998: }
5999:
6000: # --------------------------------------------------------- putstore interface
6001:
1.524 raeburn 6002: sub putstore {
1.1172.2.59 raeburn 6003: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6004: if (!$udomain) { $udomain=$env{'user.domain'}; }
6005: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6006: my $uhome=&homeserver($uname,$udomain);
6007: my $items='';
1.715 albertel 6008: foreach my $key (keys(%$storehash)) {
6009: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6010: }
1.715 albertel 6011: $items=~s/\&$//;
1.716 albertel 6012: my $esc_symb=&escape($symb);
6013: my $esc_v=&escape($version);
1.715 albertel 6014: my $reply =
1.716 albertel 6015: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6016: $uhome);
1.1172.2.59 raeburn 6017: if (($tolog) && ($reply eq 'ok')) {
6018: my $namevalue='';
6019: foreach my $key (keys(%{$storehash})) {
6020: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6021: }
6022: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6023: '&host='.&escape($perlvar{'lonHostID'}).
6024: '&version='.$esc_v.
6025: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6026: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6027: }
1.715 albertel 6028: if ($reply eq 'unknown_cmd') {
1.716 albertel 6029: # gfall back to way things use to be done
1.715 albertel 6030: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6031: $uname);
1.524 raeburn 6032: }
1.715 albertel 6033: return $reply;
6034: }
6035:
6036: sub old_putstore {
1.716 albertel 6037: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6038: if (!$udomain) { $udomain=$env{'user.domain'}; }
6039: if (!$uname) { $uname=$env{'user.name'}; }
6040: my $uhome=&homeserver($uname,$udomain);
6041: my %newstorehash;
1.800 albertel 6042: foreach my $item (keys(%$storehash)) {
6043: my $key = $version.':'.&escape($symb).':'.$item;
6044: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6045: }
6046: my $items='';
6047: my %allitems = ();
1.800 albertel 6048: foreach my $item (keys(%newstorehash)) {
6049: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6050: my $key = $1.':keys:'.$2;
6051: $allitems{$key} .= $3.':';
6052: }
1.800 albertel 6053: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6054: }
1.800 albertel 6055: foreach my $item (keys(%allitems)) {
6056: $allitems{$item} =~ s/\:$//;
6057: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6058: }
6059: $items=~s/\&$//;
6060: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6061: }
6062:
1.47 www 6063: # ------------------------------------------------------ critical put interface
6064:
6065: sub cput {
1.134 albertel 6066: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6067: if (!$udomain) { $udomain=$env{'user.domain'}; }
6068: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6069: my $uhome=&homeserver($uname,$udomain);
1.47 www 6070: my $items='';
1.800 albertel 6071: foreach my $item (keys(%$storehash)) {
6072: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6073: }
1.47 www 6074: $items=~s/\&$//;
1.134 albertel 6075: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6076: }
6077:
6078: # -------------------------------------------------------------- eget interface
6079:
6080: sub eget {
1.133 albertel 6081: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6082: my $items='';
1.800 albertel 6083: foreach my $item (@$storearr) {
6084: $items.=&escape($item).'&';
1.191 harris41 6085: }
1.12 www 6086: $items=~s/\&$//;
1.620 albertel 6087: if (!$udomain) { $udomain=$env{'user.domain'}; }
6088: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6089: my $uhome=&homeserver($uname,$udomain);
6090: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6091: my @pairs=split(/\&/,$rep);
6092: my %returnhash=();
1.42 www 6093: my $i=0;
1.800 albertel 6094: foreach my $item (@$storearr) {
6095: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6096: $i++;
1.191 harris41 6097: }
1.12 www 6098: return %returnhash;
6099: }
6100:
1.667 albertel 6101: # ------------------------------------------------------------ tmpput interface
6102: sub tmpput {
1.802 raeburn 6103: my ($storehash,$server,$context)=@_;
1.667 albertel 6104: my $items='';
1.800 albertel 6105: foreach my $item (keys(%$storehash)) {
6106: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6107: }
6108: $items=~s/\&$//;
1.802 raeburn 6109: if (defined($context)) {
6110: $items .= ':'.&escape($context);
6111: }
1.667 albertel 6112: return &reply("tmpput:$items",$server);
6113: }
6114:
6115: # ------------------------------------------------------------ tmpget interface
6116: sub tmpget {
1.688 albertel 6117: my ($token,$server)=@_;
6118: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6119: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6120: my %returnhash;
6121: foreach my $item (split(/\&/,$rep)) {
6122: my ($key,$value)=split(/=/,$item);
1.951 raeburn 6123: next if ($key =~ /^error: 2 /);
1.667 albertel 6124: $returnhash{&unescape($key)}=&thaw_unescape($value);
6125: }
6126: return %returnhash;
6127: }
6128:
1.1113 raeburn 6129: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6130: sub tmpdel {
6131: my ($token,$server)=@_;
6132: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6133: return &reply("tmpdel:$token",$server);
6134: }
6135:
1.1172.2.13 raeburn 6136: # ------------------------------------------------------------ get_timebased_id
6137:
6138: sub get_timebased_id {
6139: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6140: $maxtries) = @_;
6141: my ($newid,$error,$dellock);
6142: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6143: return ('','ok','invalid call to get suffix');
6144: }
6145:
6146: # set defaults for any optional args for which values were not supplied
6147: if ($who eq '') {
6148: $who = $env{'user.name'}.':'.$env{'user.domain'};
6149: }
6150: if (!$locktries) {
6151: $locktries = 3;
6152: }
6153: if (!$maxtries) {
6154: $maxtries = 10;
6155: }
6156:
6157: if (($cdom eq '') || ($cnum eq '')) {
6158: if ($env{'request.course.id'}) {
6159: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6160: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6161: }
6162: if (($cdom eq '') || ($cnum eq '')) {
6163: return ('','ok','call to get suffix not in course context');
6164: }
6165: }
6166:
6167: # construct locking item
6168: my $lockhash = {
6169: $prefix."\0".'locked_'.$keyid => $who,
6170: };
6171: my $tries = 0;
6172:
6173: # attempt to get lock on nohist_$namespace file
6174: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6175: while (($gotlock ne 'ok') && $tries <$locktries) {
6176: $tries ++;
6177: sleep 1;
6178: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6179: }
6180:
6181: # attempt to get unique identifier, based on current timestamp
6182: if ($gotlock eq 'ok') {
6183: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6184: my $id = time;
6185: $newid = $id;
1.1172.2.56 raeburn 6186: if ($idtype eq 'addcode') {
6187: $newid .= &sixnum_code();
6188: }
1.1172.2.13 raeburn 6189: my $idtries = 0;
6190: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6191: if ($idtype eq 'concat') {
6192: $newid = $id.$idtries;
1.1172.2.56 raeburn 6193: } elsif ($idtype eq 'addcode') {
6194: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 6195: } else {
6196: $newid ++;
6197: }
6198: $idtries ++;
6199: }
6200: if (!exists($inuse{$prefix."\0".$newid})) {
6201: my %new_item = (
6202: $prefix."\0".$newid => $who,
6203: );
6204: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6205: $cdom,$cnum);
6206: if ($putresult ne 'ok') {
6207: undef($newid);
6208: $error = 'error saving new item: '.$putresult;
6209: }
6210: } else {
1.1172.2.56 raeburn 6211: undef($newid);
1.1172.2.13 raeburn 6212: $error = ('error: no unique suffix available for the new item ');
6213: }
6214: # remove lock
6215: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6216: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6217: } else {
6218: $error = "error: could not obtain lockfile\n";
6219: $dellock = 'ok';
1.1172.2.58 raeburn 6220: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6221: $dellock = 'nolock';
6222: }
1.1172.2.13 raeburn 6223: }
6224: return ($newid,$dellock,$error);
6225: }
6226:
1.1172.2.56 raeburn 6227: sub sixnum_code {
6228: my $code;
6229: for (0..6) {
6230: $code .= int( rand(9) );
6231: }
6232: return $code;
6233: }
6234:
1.765 albertel 6235: # -------------------------------------------------- portfolio access checking
6236:
6237: sub portfolio_access {
1.1172.2.77 raeburn 6238: my ($requrl,$clientip) = @_;
1.765 albertel 6239: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 6240: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6241: if ($result) {
6242: my %setters;
6243: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6244: my ($startblock,$endblock) =
6245: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6246: if ($startblock && $endblock) {
6247: return 'B';
6248: }
6249: } else {
6250: my ($startblock,$endblock) =
6251: &Apache::loncommon::blockcheck(\%setters,'port');
6252: if ($startblock && $endblock) {
6253: return 'B';
6254: }
6255: }
6256: }
1.765 albertel 6257: if ($result eq 'ok') {
1.766 albertel 6258: return 'F';
1.765 albertel 6259: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6260: return 'A';
1.765 albertel 6261: }
1.766 albertel 6262: return '';
1.765 albertel 6263: }
6264:
6265: sub get_portfolio_access {
1.1172.2.77 raeburn 6266: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6267:
6268: if (!ref($access_hash)) {
6269: my $current_perms = &get_portfile_permissions($udom,$unum);
6270: my %access_controls = &get_access_controls($current_perms,$group,
6271: $file_name);
6272: $access_hash = $access_controls{$file_name};
6273: }
6274:
1.1172.2.77 raeburn 6275: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6276: my $now = time;
6277: if (ref($access_hash) eq 'HASH') {
6278: foreach my $key (keys(%{$access_hash})) {
6279: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6280: if ($start > $now) {
6281: next;
6282: }
6283: if ($end && $end<$now) {
6284: next;
6285: }
6286: if ($scope eq 'public') {
6287: $public = $key;
6288: last;
6289: } elsif ($scope eq 'guest') {
6290: $guest = $key;
6291: } elsif ($scope eq 'domains') {
6292: push(@domains,$key);
6293: } elsif ($scope eq 'users') {
6294: push(@users,$key);
6295: } elsif ($scope eq 'course') {
6296: push(@courses,$key);
6297: } elsif ($scope eq 'group') {
6298: push(@groups,$key);
1.1172.2.77 raeburn 6299: } elsif ($scope eq 'ip') {
6300: push(@ips,$key);
1.765 albertel 6301: }
6302: }
6303: if ($public) {
6304: return 'ok';
1.1172.2.77 raeburn 6305: } elsif (@ips > 0) {
6306: my $allowed;
6307: foreach my $ipkey (@ips) {
6308: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6309: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6310: $allowed = 1;
6311: last;
6312: }
6313: }
6314: }
6315: if ($allowed) {
6316: return 'ok';
6317: }
1.765 albertel 6318: }
6319: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6320: if ($guest) {
6321: return $guest;
6322: }
6323: } else {
6324: if (@domains > 0) {
6325: foreach my $domkey (@domains) {
6326: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6327: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6328: return 'ok';
6329: }
6330: }
6331: }
6332: }
6333: if (@users > 0) {
6334: foreach my $userkey (@users) {
1.865 raeburn 6335: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6336: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6337: if (ref($item) eq 'HASH') {
6338: if (($item->{'uname'} eq $env{'user.name'}) &&
6339: ($item->{'udom'} eq $env{'user.domain'})) {
6340: return 'ok';
6341: }
6342: }
6343: }
6344: }
1.765 albertel 6345: }
6346: }
6347: my %roleshash;
6348: my @courses_and_groups = @courses;
6349: push(@courses_and_groups,@groups);
6350: if (@courses_and_groups > 0) {
6351: my (%allgroups,%allroles);
6352: my ($start,$end,$role,$sec,$group);
6353: foreach my $envkey (%env) {
1.1060 raeburn 6354: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6355: my $cid = $2.'_'.$3;
6356: if ($1 eq 'gr') {
6357: $group = $4;
6358: $allgroups{$cid}{$group} = $env{$envkey};
6359: } else {
6360: if ($4 eq '') {
6361: $sec = 'none';
6362: } else {
6363: $sec = $4;
6364: }
6365: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6366: }
1.811 albertel 6367: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6368: my $cid = $2.'_'.$3;
6369: if ($4 eq '') {
6370: $sec = 'none';
6371: } else {
6372: $sec = $4;
6373: }
6374: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6375: }
6376: }
6377: if (keys(%allroles) == 0) {
6378: return;
6379: }
6380: foreach my $key (@courses_and_groups) {
6381: my %content = %{$$access_hash{$key}};
6382: my $cnum = $content{'number'};
6383: my $cdom = $content{'domain'};
6384: my $cid = $cdom.'_'.$cnum;
6385: if (!exists($allroles{$cid})) {
6386: next;
6387: }
6388: foreach my $role_id (keys(%{$content{'roles'}})) {
6389: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6390: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6391: my @status = @{$content{'roles'}{$role_id}{'access'}};
6392: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6393: foreach my $role (keys(%{$allroles{$cid}})) {
6394: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6395: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6396: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6397: if (grep/^all$/,@sections) {
6398: return 'ok';
6399: } else {
6400: if (grep/^$sec$/,@sections) {
6401: return 'ok';
6402: }
6403: }
6404: }
6405: }
6406: if (keys(%{$allgroups{$cid}}) == 0) {
6407: if (grep/^none$/,@groups) {
6408: return 'ok';
6409: }
6410: } else {
6411: if (grep/^all$/,@groups) {
6412: return 'ok';
6413: }
6414: foreach my $group (keys(%{$allgroups{$cid}})) {
6415: if (grep/^$group$/,@groups) {
6416: return 'ok';
6417: }
6418: }
6419: }
6420: }
6421: }
6422: }
6423: }
6424: }
6425: if ($guest) {
6426: return $guest;
6427: }
6428: }
6429: }
6430: return;
6431: }
6432:
6433: sub course_group_datechecker {
6434: my ($dates,$now,$status) = @_;
6435: my ($start,$end) = split(/\./,$dates);
6436: if (!$start && !$end) {
6437: return 'ok';
6438: }
6439: if (grep/^active$/,@{$status}) {
6440: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6441: return 'ok';
6442: }
6443: }
6444: if (grep/^previous$/,@{$status}) {
6445: if ($end > $now ) {
6446: return 'ok';
6447: }
6448: }
6449: if (grep/^future$/,@{$status}) {
6450: if ($start > $now) {
6451: return 'ok';
6452: }
6453: }
6454: return;
6455: }
6456:
6457: sub parse_portfolio_url {
6458: my ($url) = @_;
6459:
6460: my ($type,$udom,$unum,$group,$file_name);
6461:
1.823 albertel 6462: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6463: $type = 1;
6464: $udom = $1;
6465: $unum = $2;
6466: $file_name = $3;
1.823 albertel 6467: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6468: $type = 2;
6469: $udom = $1;
6470: $unum = $2;
6471: $group = $3;
6472: $file_name = $3.'/'.$4;
6473: }
6474: if (wantarray) {
6475: return ($type,$udom,$unum,$file_name,$group);
6476: }
6477: return $type;
6478: }
6479:
6480: sub is_portfolio_url {
6481: my ($url) = @_;
6482: return scalar(&parse_portfolio_url($url));
6483: }
6484:
1.798 raeburn 6485: sub is_portfolio_file {
6486: my ($file) = @_;
1.820 raeburn 6487: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6488: return 1;
6489: }
6490: return;
6491: }
6492:
1.976 raeburn 6493: sub usertools_access {
1.1084 raeburn 6494: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6495: my ($access,%tools);
6496: if ($context eq '') {
6497: $context = 'tools';
6498: }
6499: if ($context eq 'requestcourses') {
6500: %tools = (
6501: official => 1,
6502: unofficial => 1,
1.1006 raeburn 6503: community => 1,
1.1172.2.37 raeburn 6504: textbook => 1,
1.985 raeburn 6505: );
1.1172.2.9 raeburn 6506: } elsif ($context eq 'requestauthor') {
6507: %tools = (
6508: requestauthor => 1,
6509: );
1.985 raeburn 6510: } else {
6511: %tools = (
6512: aboutme => 1,
6513: blog => 1,
1.1172.2.6 raeburn 6514: webdav => 1,
1.985 raeburn 6515: portfolio => 1,
6516: );
6517: }
1.976 raeburn 6518: return if (!defined($tools{$tool}));
6519:
1.1172.2.35 raeburn 6520: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6521: $udom = $env{'user.domain'};
6522: $uname = $env{'user.name'};
6523: }
6524:
1.978 raeburn 6525: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6526: if ($action ne 'reload') {
1.985 raeburn 6527: if ($context eq 'requestcourses') {
6528: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6529: } elsif ($context eq 'requestauthor') {
6530: return $env{'environment.canrequest.author'};
1.985 raeburn 6531: } else {
6532: return $env{'environment.availabletools.'.$tool};
6533: }
6534: }
1.976 raeburn 6535: }
6536:
1.1172.2.9 raeburn 6537: my ($toolstatus,$inststatus,$envkey);
6538: if ($context eq 'requestauthor') {
6539: $envkey = $context;
6540: } else {
6541: $envkey = $context.'.'.$tool;
6542: }
1.976 raeburn 6543:
1.985 raeburn 6544: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6545: ($action ne 'reload')) {
1.1172.2.9 raeburn 6546: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6547: $inststatus = $env{'environment.inststatus'};
6548: } else {
1.1084 raeburn 6549: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6550: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6551: $inststatus = $userenvref->{'inststatus'};
6552: } else {
1.1172.2.9 raeburn 6553: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6554: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6555: $inststatus = $userenv{'inststatus'};
6556: }
1.976 raeburn 6557: }
6558:
6559: if ($toolstatus ne '') {
6560: if ($toolstatus) {
6561: $access = 1;
6562: } else {
6563: $access = 0;
6564: }
6565: return $access;
6566: }
6567:
1.1084 raeburn 6568: my ($is_adv,%domdef);
6569: if (ref($is_advref) eq 'HASH') {
6570: $is_adv = $is_advref->{'is_adv'};
6571: } else {
6572: $is_adv = &is_advanced_user($udom,$uname);
6573: }
6574: if (ref($domdefref) eq 'HASH') {
6575: %domdef = %{$domdefref};
6576: } else {
6577: %domdef = &get_domain_defaults($udom);
6578: }
1.976 raeburn 6579: if (ref($domdef{$tool}) eq 'HASH') {
6580: if ($is_adv) {
6581: if ($domdef{$tool}{'_LC_adv'} ne '') {
6582: if ($domdef{$tool}{'_LC_adv'}) {
6583: $access = 1;
6584: } else {
6585: $access = 0;
6586: }
6587: return $access;
6588: }
6589: }
6590: if ($inststatus ne '') {
6591: my ($hasaccess,$hasnoaccess);
6592: foreach my $affiliation (split(/:/,$inststatus)) {
6593: if ($domdef{$tool}{$affiliation} ne '') {
6594: if ($domdef{$tool}{$affiliation}) {
6595: $hasaccess = 1;
6596: } else {
6597: $hasnoaccess = 1;
6598: }
6599: }
6600: }
6601: if ($hasaccess || $hasnoaccess) {
6602: if ($hasaccess) {
6603: $access = 1;
6604: } elsif ($hasnoaccess) {
6605: $access = 0;
6606: }
6607: return $access;
6608: }
6609: } else {
6610: if ($domdef{$tool}{'default'} ne '') {
6611: if ($domdef{$tool}{'default'}) {
6612: $access = 1;
6613: } elsif ($domdef{$tool}{'default'} == 0) {
6614: $access = 0;
6615: }
6616: return $access;
6617: }
6618: }
6619: } else {
1.1172.2.6 raeburn 6620: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6621: $access = 1;
6622: } else {
6623: $access = 0;
6624: }
1.976 raeburn 6625: return $access;
6626: }
6627: }
6628:
1.1050 raeburn 6629: sub is_course_owner {
6630: my ($cdom,$cnum,$udom,$uname) = @_;
6631: if (($udom eq '') || ($uname eq '')) {
6632: $udom = $env{'user.domain'};
6633: $uname = $env{'user.name'};
6634: }
6635: unless (($udom eq '') || ($uname eq '')) {
6636: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6637: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6638: return 1;
6639: } else {
6640: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6641: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6642: return 1;
6643: }
6644: }
6645: }
6646: }
6647: return;
6648: }
6649:
1.976 raeburn 6650: sub is_advanced_user {
6651: my ($udom,$uname) = @_;
1.1085 raeburn 6652: if ($udom ne '' && $uname ne '') {
6653: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6654: if (wantarray) {
6655: return ($env{'user.adv'},$env{'user.author'});
6656: } else {
6657: return $env{'user.adv'};
6658: }
1.1085 raeburn 6659: }
6660: }
1.976 raeburn 6661: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6662: my %allroles;
1.1128 raeburn 6663: my ($is_adv,$is_author);
1.976 raeburn 6664: foreach my $role (keys(%roleshash)) {
6665: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6666: my $area = '/'.$tdomain.'/'.$trest;
6667: if ($sec ne '') {
6668: $area .= '/'.$sec;
6669: }
6670: if (($area ne '') && ($trole ne '')) {
6671: my $spec=$trole.'.'.$area;
6672: if ($trole =~ /^cr\//) {
6673: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6674: } elsif ($trole ne 'gr') {
6675: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6676: }
1.1128 raeburn 6677: if ($trole eq 'au') {
6678: $is_author = 1;
6679: }
1.976 raeburn 6680: }
6681: }
6682: foreach my $role (keys(%allroles)) {
6683: last if ($is_adv);
6684: foreach my $item (split(/:/,$allroles{$role})) {
6685: if ($item ne '') {
6686: my ($privilege,$restrictions)=split(/&/,$item);
6687: if ($privilege eq 'adv') {
6688: $is_adv = 1;
6689: last;
6690: }
6691: }
6692: }
6693: }
1.1128 raeburn 6694: if (wantarray) {
6695: return ($is_adv,$is_author);
6696: }
1.976 raeburn 6697: return $is_adv;
6698: }
1.798 raeburn 6699:
1.1035 raeburn 6700: sub check_can_request {
1.1036 raeburn 6701: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6702: my $canreq = 0;
6703: my ($types,$typename) = &Apache::loncommon::course_types();
6704: my @options = ('approval','validate','autolimit');
6705: my $optregex = join('|',@options);
6706: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6707: foreach my $type (@{$types}) {
6708: if (&usertools_access($env{'user.name'},
6709: $env{'user.domain'},
6710: $type,undef,'requestcourses')) {
6711: $canreq ++;
1.1036 raeburn 6712: if (ref($request_domains) eq 'HASH') {
6713: push(@{$request_domains->{$type}},$env{'user.domain'});
6714: }
1.1035 raeburn 6715: if ($dom eq $env{'user.domain'}) {
6716: $can_request->{$type} = 1;
6717: }
6718: }
6719: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6720: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6721: if (@curr > 0) {
1.1036 raeburn 6722: foreach my $item (@curr) {
6723: if (ref($request_domains) eq 'HASH') {
6724: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6725: if ($otherdom ne '') {
6726: if (ref($request_domains->{$type}) eq 'ARRAY') {
6727: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6728: push(@{$request_domains->{$type}},$otherdom);
6729: }
6730: } else {
6731: push(@{$request_domains->{$type}},$otherdom);
6732: }
6733: }
6734: }
6735: }
6736: unless($dom eq $env{'user.domain'}) {
6737: $canreq ++;
1.1035 raeburn 6738: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6739: $can_request->{$type} = 1;
6740: }
6741: }
6742: }
6743: }
6744: }
6745: }
6746: return $canreq;
6747: }
6748:
1.341 www 6749: # ---------------------------------------------- Custom access rule evaluation
6750:
6751: sub customaccess {
6752: my ($priv,$uri)=@_;
1.807 albertel 6753: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6754: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6755: $udom = &LONCAPA::clean_domain($udom);
6756: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6757: my $access=0;
1.800 albertel 6758: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6759: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6760: if ($type eq 'user') {
6761: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6762: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6763: if ($tdom) {
6764: if ($tdom ne $env{'user.domain'}) { next; }
6765: }
1.896 albertel 6766: if ($tuname) {
6767: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6768: }
6769: $access=($effect eq 'allow');
6770: last;
6771: }
6772: } else {
6773: if ($role) {
6774: if ($role ne $urole) { next; }
6775: }
6776: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6777: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6778: if ($tdom) {
6779: if ($tdom ne $udom) { next; }
6780: }
6781: if ($tcrs) {
6782: if ($tcrs ne $ucrs) { next; }
6783: }
6784: if ($tsec) {
6785: if ($tsec ne $usec) { next; }
6786: }
6787: $access=($effect eq 'allow');
6788: last;
6789: }
6790: if ($realm eq '' && $role eq '') {
6791: $access=($effect eq 'allow');
6792: }
1.402 bowersj2 6793: }
1.341 www 6794: }
6795: return $access;
6796: }
6797:
1.103 harris41 6798: # ------------------------------------------------- Check for a user privilege
1.12 www 6799:
6800: sub allowed {
1.1172.2.65 raeburn 6801: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 6802: my $ver_orguri=$uri;
1.439 www 6803: $uri=&deversion($uri);
1.152 www 6804: my $orguri=$uri;
1.52 www 6805: $uri=&declutter($uri);
1.809 raeburn 6806:
1.810 raeburn 6807: if ($priv eq 'evb') {
6808: # Evade communication block restrictions for specified role in a course
6809: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6810: return $1;
6811: } else {
6812: return;
6813: }
6814: }
6815:
1.620 albertel 6816: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6817: # Free bre access to adm and meta resources
1.775 albertel 6818: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6819: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6820: && ($priv eq 'bre')) {
1.14 www 6821: return 'F';
1.159 www 6822: }
6823:
1.545 banghart 6824: # Free bre access to user's own portfolio contents
1.714 raeburn 6825: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6826: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6827: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6828: my %setters;
6829: my ($startblock,$endblock) =
6830: &Apache::loncommon::blockcheck(\%setters,'port');
6831: if ($startblock && $endblock) {
6832: return 'B';
6833: } else {
6834: return 'F';
6835: }
1.545 banghart 6836: }
6837:
1.762 raeburn 6838: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6839: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6840: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6841: if (exists($env{'request.course.id'})) {
6842: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6843: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6844: if (($domain eq $cdom) && ($name eq $cnum)) {
6845: my $courseprivid=$env{'request.course.id'};
6846: $courseprivid=~s/\_/\//;
6847: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6848: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6849: return $1;
1.762 raeburn 6850: } else {
6851: if ($env{'request.course.sec'}) {
6852: $courseprivid.='/'.$env{'request.course.sec'};
6853: }
6854: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6855: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6856: return $2;
6857: }
1.714 raeburn 6858: }
6859: }
6860: }
6861: }
6862:
1.159 www 6863: # Free bre to public access
6864:
6865: if ($priv eq 'bre') {
1.238 www 6866: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6867: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6868: return 'F';
6869: }
1.238 www 6870: if ($copyright eq 'priv') {
6871: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6872: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6873: return '';
6874: }
6875: }
6876: if ($copyright eq 'domain') {
6877: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6878: unless (($env{'user.domain'} eq $1) ||
6879: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6880: return '';
6881: }
1.262 matthew 6882: }
1.620 albertel 6883: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6884: # Library role, so allow browsing of resources in this domain.
6885: return 'F';
1.238 www 6886: }
1.341 www 6887: if ($copyright eq 'custom') {
6888: unless (&customaccess($priv,$uri)) { return ''; }
6889: }
1.14 www 6890: }
1.264 matthew 6891: # Domain coordinator is trying to create a course
1.620 albertel 6892: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6893: # uri is the requested domain in this case.
6894: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6895: # a role of dc for the domain in question.
1.620 albertel 6896: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6897: }
1.29 www 6898:
1.52 www 6899: my $thisallowed='';
6900: my $statecond=0;
6901: my $courseprivid='';
6902:
1.1039 raeburn 6903: my $ownaccess;
1.1043 raeburn 6904: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6905: if (($priv eq 'bro') && ($env{'user.author'})) {
6906: if ($uri eq '') {
6907: $ownaccess = 1;
6908: } else {
6909: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6910: my $udom = $env{'user.domain'};
6911: my $uname = $env{'user.name'};
6912: if ($uri =~ m{^\Q$udom\E/?$}) {
6913: $ownaccess = 1;
1.1040 raeburn 6914: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6915: unless ($uri =~ m{\.\./}) {
6916: $ownaccess = 1;
6917: }
6918: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6919: my $now = time;
6920: if ($uri =~ m{^([^/]+)/?$}) {
6921: my $adom = $1;
6922: foreach my $key (keys(%env)) {
1.1042 raeburn 6923: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6924: my ($start,$end) = split('.',$env{$key});
6925: if (($now >= $start) && (!$end || $end < $now)) {
6926: $ownaccess = 1;
6927: last;
6928: }
6929: }
6930: }
6931: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6932: my $adom = $1;
6933: my $aname = $2;
1.1042 raeburn 6934: foreach my $role ('ca','aa') {
6935: if ($env{"user.role.$role./$adom/$aname"}) {
6936: my ($start,$end) =
6937: split('.',$env{"user.role.$role./$adom/$aname"});
6938: if (($now >= $start) && (!$end || $end < $now)) {
6939: $ownaccess = 1;
6940: last;
6941: }
1.1039 raeburn 6942: }
6943: }
6944: }
6945: }
6946: }
6947: }
6948: }
6949:
1.52 www 6950: # Course
6951:
1.620 albertel 6952: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6953: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6954: $thisallowed.=$1;
6955: }
1.52 www 6956: }
1.29 www 6957:
1.52 www 6958: # Domain
6959:
1.620 albertel 6960: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6961: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6962: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6963: $thisallowed.=$1;
6964: }
1.12 www 6965: }
1.52 www 6966:
1.1141 raeburn 6967: # User who is not author or co-author might still be able to edit
6968: # resource of an author in the domain (e.g., if Domain Coordinator).
6969: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6970: (&allowed('mdc',$env{'request.course.id'}))) {
6971: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6972: $thisallowed.=$1;
6973: }
6974: }
6975:
1.52 www 6976: # Course: uri itself is a course
1.66 www 6977: my $courseuri=$uri;
6978: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6979: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6980:
1.620 albertel 6981: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6982: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6983: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6984: $thisallowed.=$1;
6985: }
1.12 www 6986: }
1.29 www 6987:
1.665 albertel 6988: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6989: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6990: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6991: $thisallowed='';
1.671 raeburn 6992: my ($match)=&is_on_map($uri);
6993: if ($match) {
6994: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6995: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 6996: my $value = $1;
6997: if ($noblockcheck) {
6998: $thisallowed.=$value;
1.1162 raeburn 6999: } else {
1.1172.2.65 raeburn 7000: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7001: if (@blockers > 0) {
7002: $thisallowed = 'B';
7003: } else {
7004: $thisallowed.=$value;
7005: }
1.1162 raeburn 7006: }
1.671 raeburn 7007: }
7008: } else {
1.705 albertel 7009: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7010: if ($refuri) {
7011: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7012: $thisallowed='F';
1.671 raeburn 7013: } else {
7014: $refuri=&declutter($refuri);
7015: my ($match) = &is_on_map($refuri);
7016: if ($match) {
1.1172.2.65 raeburn 7017: if ($noblockcheck) {
1.1162 raeburn 7018: $thisallowed='F';
1.1172.2.65 raeburn 7019: } else {
7020: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7021: if (@blockers > 0) {
7022: $thisallowed = 'B';
7023: } else {
7024: $thisallowed='F';
7025: }
1.1162 raeburn 7026: }
1.671 raeburn 7027: }
1.669 raeburn 7028: }
1.671 raeburn 7029: }
7030: }
1.314 www 7031: }
1.492 albertel 7032:
1.766 albertel 7033: if ($priv eq 'bre'
7034: && $thisallowed ne 'F'
7035: && $thisallowed ne '2'
7036: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 7037: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7038: }
7039:
1.52 www 7040: # Full access at system, domain or course-wide level? Exit.
1.29 www 7041: if ($thisallowed=~/F/) {
7042: return 'F';
7043: }
7044:
1.52 www 7045: # If this is generating or modifying users, exit with special codes
1.29 www 7046:
1.643 www 7047: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7048: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7049: my ($audom,$auname)=split('/',$uri);
1.643 www 7050: # no author name given, so this just checks on the general right to make a co-author in this domain
7051: unless ($auname) { return $thisallowed; }
7052: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7053: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7054: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7055: ($audom ne $env{'request.role.domain'}))) { return ''; }
7056: }
1.52 www 7057: return $thisallowed;
7058: }
7059: #
1.103 harris41 7060: # Gathered so far: system, domain and course wide privileges
1.52 www 7061: #
7062: # Course: See if uri or referer is an individual resource that is part of
7063: # the course
7064:
1.620 albertel 7065: if ($env{'request.course.id'}) {
1.232 www 7066:
1.620 albertel 7067: $courseprivid=$env{'request.course.id'};
7068: if ($env{'request.course.sec'}) {
7069: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7070: }
7071: $courseprivid=~s/\_/\//;
7072: my $checkreferer=1;
1.232 www 7073: my ($match,$cond)=&is_on_map($uri);
7074: if ($match) {
7075: $statecond=$cond;
1.620 albertel 7076: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7077: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7078: my $value = $1;
7079: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7080: if ($noblockcheck) {
1.1162 raeburn 7081: $thisallowed.=$value;
1.1172.2.65 raeburn 7082: } else {
7083: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7084: if (@blockers > 0) {
7085: $thisallowed = 'B';
7086: } else {
7087: $thisallowed.=$value;
7088: }
1.1162 raeburn 7089: }
7090: } else {
7091: $thisallowed.=$value;
7092: }
1.52 www 7093: $checkreferer=0;
7094: }
1.29 www 7095: }
1.83 www 7096:
1.148 www 7097: if ($checkreferer) {
1.620 albertel 7098: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7099: unless ($refuri) {
1.800 albertel 7100: foreach my $key (keys(%env)) {
7101: if ($key=~/^httpref\..*\*/) {
7102: my $pattern=$key;
1.156 www 7103: $pattern=~s/^httpref\.\/res\///;
1.148 www 7104: $pattern=~s/\*/\[\^\/\]\+/g;
7105: $pattern=~s/\//\\\//g;
1.152 www 7106: if ($orguri=~/$pattern/) {
1.800 albertel 7107: $refuri=$env{$key};
1.148 www 7108: }
7109: }
1.191 harris41 7110: }
1.148 www 7111: }
1.232 www 7112:
1.148 www 7113: if ($refuri) {
1.152 www 7114: $refuri=&declutter($refuri);
1.232 www 7115: my ($match,$cond)=&is_on_map($refuri);
7116: if ($match) {
7117: my $refstatecond=$cond;
1.620 albertel 7118: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7119: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7120: my $value = $1;
7121: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7122: if ($noblockcheck) {
1.1162 raeburn 7123: $thisallowed.=$value;
1.1172.2.65 raeburn 7124: } else {
7125: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7126: if (@blockers > 0) {
7127: $thisallowed = 'B';
7128: } else {
7129: $thisallowed.=$value;
7130: }
1.1162 raeburn 7131: }
7132: } else {
7133: $thisallowed.=$value;
7134: }
1.53 www 7135: $uri=$refuri;
7136: $statecond=$refstatecond;
1.52 www 7137: }
7138: }
1.148 www 7139: }
1.29 www 7140: }
1.52 www 7141: }
1.29 www 7142:
1.52 www 7143: #
1.103 harris41 7144: # Gathered now: all privileges that could apply, and condition number
1.52 www 7145: #
7146: #
7147: # Full or no access?
7148: #
1.29 www 7149:
1.52 www 7150: if ($thisallowed=~/F/) {
7151: return 'F';
7152: }
1.29 www 7153:
1.52 www 7154: unless ($thisallowed) {
7155: return '';
7156: }
1.29 www 7157:
1.52 www 7158: # Restrictions exist, deal with them
7159: #
7160: # C:according to course preferences
7161: # R:according to resource settings
7162: # L:unless locked
7163: # X:according to user session state
7164: #
7165:
7166: # Possibly locked functionality, check all courses
1.54 www 7167: # Locks might take effect only after 10 minutes cache expiration for other
7168: # courses, and 2 minutes for current course
1.52 www 7169:
7170: my $envkey;
7171: if ($thisallowed=~/L/) {
1.1000 raeburn 7172: foreach $envkey (keys(%env)) {
1.54 www 7173: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7174: my $courseid=$2;
7175: my $roleid=$1.'.'.$2;
1.92 www 7176: $courseid=~s/^\///;
1.54 www 7177: my $expiretime=600;
1.620 albertel 7178: if ($env{'request.role'} eq $roleid) {
1.54 www 7179: $expiretime=120;
7180: }
7181: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7182: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7183: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7184: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7185: }
1.620 albertel 7186: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7187: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7188: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7189: &log($env{'user.domain'},$env{'user.name'},
7190: $env{'user.home'},
1.57 www 7191: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7192: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7193: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7194: return '';
7195: }
7196: }
1.620 albertel 7197: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7198: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7199: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7200: &log($env{'user.domain'},$env{'user.name'},
7201: $env{'user.home'},
1.57 www 7202: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7203: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7204: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7205: return '';
7206: }
7207: }
7208: }
1.29 www 7209: }
1.52 www 7210: }
7211:
7212: #
7213: # Rest of the restrictions depend on selected course
7214: #
7215:
1.620 albertel 7216: unless ($env{'request.course.id'}) {
1.766 albertel 7217: if ($thisallowed eq 'A') {
7218: return 'A';
1.814 raeburn 7219: } elsif ($thisallowed eq 'B') {
7220: return 'B';
1.766 albertel 7221: } else {
7222: return '1';
7223: }
1.52 www 7224: }
1.29 www 7225:
1.52 www 7226: #
7227: # Now user is definitely in a course
7228: #
1.53 www 7229:
7230:
7231: # Course preferences
7232:
7233: if ($thisallowed=~/C/) {
1.620 albertel 7234: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7235: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7236: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7237: =~/\Q$rolecode\E/) {
1.1103 raeburn 7238: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7239: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7240: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7241: $env{'request.course.id'});
7242: }
1.237 www 7243: return '';
7244: }
7245:
1.620 albertel 7246: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7247: =~/\Q$unamedom\E/) {
1.1103 raeburn 7248: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7249: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7250: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7251: $env{'request.course.id'});
7252: }
1.54 www 7253: return '';
7254: }
1.53 www 7255: }
7256:
7257: # Resource preferences
7258:
7259: if ($thisallowed=~/R/) {
1.620 albertel 7260: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7261: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7262: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7263: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7264: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7265: }
7266: return '';
1.54 www 7267: }
1.53 www 7268: }
1.30 www 7269:
1.246 www 7270: # Restricted by state or randomout?
1.30 www 7271:
1.52 www 7272: if ($thisallowed=~/X/) {
1.620 albertel 7273: if ($env{'acc.randomout'}) {
1.579 albertel 7274: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7275: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7276: return '';
7277: }
1.247 www 7278: }
7279: if (&condval($statecond)) {
1.52 www 7280: return '2';
7281: } else {
7282: return '';
7283: }
7284: }
1.30 www 7285:
1.766 albertel 7286: if ($thisallowed eq 'A') {
7287: return 'A';
1.814 raeburn 7288: } elsif ($thisallowed eq 'B') {
7289: return 'B';
1.766 albertel 7290: }
1.52 www 7291: return 'F';
1.232 www 7292: }
1.1162 raeburn 7293:
1.1172.2.13 raeburn 7294: # ------------------------------------------- Check construction space access
7295:
7296: sub constructaccess {
7297: my ($url,$setpriv)=@_;
7298:
7299: # We do not allow editing of previous versions of files
7300: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7301:
7302: # Get username and domain from URL
7303: my ($ownername,$ownerdomain,$ownerhome);
7304:
7305: ($ownerdomain,$ownername) =
7306: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7307:
7308: # The URL does not really point to any authorspace, forget it
7309: unless (($ownername) && ($ownerdomain)) { return ''; }
7310:
7311: # Now we need to see if the user has access to the authorspace of
7312: # $ownername at $ownerdomain
7313:
7314: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7315: # Real author for this?
7316: $ownerhome = $env{'user.home'};
7317: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7318: return ($ownername,$ownerdomain,$ownerhome);
7319: }
7320: } else {
7321: # Co-author for this?
7322: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7323: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7324: $ownerhome = &homeserver($ownername,$ownerdomain);
7325: return ($ownername,$ownerdomain,$ownerhome);
7326: }
7327: }
7328:
7329: # We don't have any access right now. If we are not possibly going to do anything about this,
7330: # we might as well leave
7331: unless ($setpriv) { return ''; }
7332:
7333: # Backdoor access?
7334: my $allowed=&allowed('eco',$ownerdomain);
7335: # Nope
7336: unless ($allowed) { return ''; }
7337: # Looks like we may have access, but could be locked by the owner of the construction space
7338: if ($allowed eq 'U') {
7339: my %blocked=&get('environment',['domcoord.author'],
7340: $ownerdomain,$ownername);
7341: # Is blocked by owner
7342: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7343: }
7344: if (($allowed eq 'F') || ($allowed eq 'U')) {
7345: # Grant temporary access
7346: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7347: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7348: if (!$update) { $update = $then; }
7349: my $refresh=$env{'user.refresh.time'};
7350: if (!$refresh) { $refresh = $update; }
7351: my $now = time;
7352: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7353: $now,'ca','constructaccess');
7354: $ownerhome = &homeserver($ownername,$ownerdomain);
7355: return($ownername,$ownerdomain,$ownerhome);
7356: }
7357: # No business here
7358: return '';
7359: }
7360:
1.1172.2.66 raeburn 7361: # ----------------------------------------------------------- Content Blocking
7362:
7363: {
7364: # Caches for faster Course Contents display where content blocking
7365: # is in operation (i.e., interval param set) for timed quiz.
7366: #
7367: # User for whom data are being temporarily cached.
7368: my $cacheduser='';
7369: # Cached blockers for this user (a hash of blocking items).
7370: my %cachedblockers=();
7371: # When the data were last cached.
7372: my $cachedlast='';
7373:
7374: sub load_all_blockers {
7375: my ($uname,$udom,$blocks)=@_;
7376: if (($uname ne '') && ($udom ne '')) {
7377: if (($cacheduser eq $uname.':'.$udom) &&
7378: (abs($cachedlast-time)<5)) {
7379: return;
7380: }
7381: }
7382: $cachedlast=time;
7383: $cacheduser=$uname.':'.$udom;
7384: %cachedblockers = &get_commblock_resources($blocks);
7385: }
7386:
1.1162 raeburn 7387: sub get_comm_blocks {
7388: my ($cdom,$cnum) = @_;
7389: if ($cdom eq '' || $cnum eq '') {
7390: return unless ($env{'request.course.id'});
7391: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7392: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7393: }
7394: my %commblocks;
7395: my $hashid=$cdom.'_'.$cnum;
7396: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7397: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7398: %commblocks = %{$blocksref};
7399: } else {
7400: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7401: my $cachetime = 600;
7402: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7403: }
7404: return %commblocks;
7405: }
7406:
1.1172.2.66 raeburn 7407: sub get_commblock_resources {
7408: my ($blocks) = @_;
7409: my %blockers = ();
7410: return %blockers unless ($env{'request.course.id'});
7411: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7412: my %commblocks;
7413: if (ref($blocks) eq 'HASH') {
7414: %commblocks = %{$blocks};
7415: } else {
7416: %commblocks = &get_comm_blocks();
7417: }
1.1172.2.66 raeburn 7418: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 7419: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 7420: return %blockers unless (ref($navmap));
7421: my $now = time;
1.1162 raeburn 7422: foreach my $block (keys(%commblocks)) {
7423: if ($block =~ /^(\d+)____(\d+)$/) {
7424: my ($start,$end) = ($1,$2);
7425: if ($start <= $now && $end >= $now) {
7426: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7427: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7428: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 7429: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7430: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7431: }
7432: }
7433: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 7434: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7435: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7436: }
7437: }
7438: }
7439: }
7440: }
7441: } elsif ($block =~ /^firstaccess____(.+)$/) {
7442: my $item = $1;
1.1163 raeburn 7443: my @to_test;
1.1162 raeburn 7444: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7445: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66 raeburn 7446: my @interval;
7447: my $type = 'map';
7448: if ($item eq 'course') {
7449: $type = 'course';
7450: @interval=&EXT("resource.0.interval");
7451: } else {
7452: if ($item =~ /___\d+___/) {
7453: $type = 'resource';
7454: @interval=&EXT("resource.0.interval",$item);
7455: if (ref($navmap)) {
7456: my $res = $navmap->getBySymb($item);
7457: push(@to_test,$res);
7458: }
1.1162 raeburn 7459: } else {
1.1172.2.66 raeburn 7460: my $mapsymb = &symbread($item,1);
7461: if ($mapsymb) {
7462: if (ref($navmap)) {
7463: my $mapres = $navmap->getBySymb($mapsymb);
7464: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7465: foreach my $res (@to_test) {
7466: my $symb = $res->symb();
7467: next if ($symb eq $mapsymb);
7468: if ($symb ne '') {
7469: @interval=&EXT("resource.0.interval",$symb);
7470: if ($interval[1] eq 'map') {
7471: last;
1.1162 raeburn 7472: }
7473: }
7474: }
7475: }
7476: }
7477: }
1.1172.2.66 raeburn 7478: }
7479: if ($interval[0] =~ /^\d+$/) {
7480: my $first_access;
7481: if ($type eq 'resource') {
7482: $first_access=&get_first_access($interval[1],$item);
7483: } elsif ($type eq 'map') {
7484: $first_access=&get_first_access($interval[1],undef,$item);
7485: } else {
7486: $first_access=&get_first_access($interval[1]);
7487: }
7488: if ($first_access) {
7489: my $timesup = $first_access+$interval[0];
7490: if ($timesup > $now) {
7491: my $activeblock;
7492: foreach my $res (@to_test) {
7493: if ($res->answerable()) {
7494: $activeblock = 1;
7495: last;
7496: }
7497: }
7498: if ($activeblock) {
7499: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7500: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7501: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7502: }
7503: }
7504: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7505: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7506: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7507: }
1.1162 raeburn 7508: }
7509: }
7510: }
7511: }
7512: }
7513: }
7514: }
7515: }
7516: }
1.1172.2.66 raeburn 7517: return %blockers;
1.1162 raeburn 7518: }
7519:
1.1172.2.66 raeburn 7520: sub has_comm_blocking {
7521: my ($priv,$symb,$uri,$blocks) = @_;
7522: my @blockers;
7523: return unless ($env{'request.course.id'});
7524: return unless ($priv eq 'bre');
7525: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7526: return if ($env{'request.state'} eq 'construct');
7527: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7528: return unless (keys(%cachedblockers) > 0);
7529: my (%possibles,@symbs);
7530: if (!$symb) {
7531: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7532: }
1.1172.2.66 raeburn 7533: if ($symb) {
7534: @symbs = ($symb);
7535: } elsif (keys(%possibles)) {
7536: @symbs = keys(%possibles);
7537: }
7538: my $noblock;
7539: foreach my $symb (@symbs) {
7540: last if ($noblock);
7541: my ($map,$resid,$resurl)=&decode_symb($symb);
7542: foreach my $block (keys(%cachedblockers)) {
7543: if ($block =~ /^firstaccess____(.+)$/) {
7544: my $item = $1;
7545: if (($item eq $map) || ($item eq $symb)) {
7546: $noblock = 1;
7547: last;
7548: }
1.1162 raeburn 7549: }
1.1172.2.66 raeburn 7550: if (ref($cachedblockers{$block}) eq 'HASH') {
7551: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7552: if ($cachedblockers{$block}{'resources'}{$symb}) {
7553: unless (grep(/^\Q$block\E$/,@blockers)) {
7554: push(@blockers,$block);
7555: }
7556: }
7557: }
7558: }
7559: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7560: if ($cachedblockers{$block}{'maps'}{$map}) {
7561: unless (grep(/^\Q$block\E$/,@blockers)) {
7562: push(@blockers,$block);
7563: }
7564: }
1.1162 raeburn 7565: }
7566: }
7567: }
1.1172.2.66 raeburn 7568: return if ($noblock);
7569: return @blockers;
7570: }
1.1162 raeburn 7571: }
7572:
1.1172.2.66 raeburn 7573: # -------------------------------- Deversion and split uri into path an filename
7574:
1.1133 foxr 7575: #
1.1172.2.66 raeburn 7576: # Removes the version from a URI and
1.1133 foxr 7577: # splits it in to its filename and path to the filename.
7578: # Seems like File::Basename could have done this more clearly.
7579: # Parameters:
7580: # $uri - input URI
7581: # Returns:
7582: # Two element list consisting of
7583: # $pathname - the URI up to and excluding the trailing /
7584: # $filename - The part of the URI following the last /
7585: # NOTE:
7586: # Another realization of this is simply:
7587: # use File::Basename;
7588: # ...
7589: # $uri = shift;
7590: # $filename = basename($uri);
7591: # $path = dirname($uri);
7592: # return ($filename, $path);
7593: #
7594: # The implementation below is probably faster however.
7595: #
1.710 albertel 7596: sub split_uri_for_cond {
7597: my $uri=&deversion(&declutter(shift));
7598: my @uriparts=split(/\//,$uri);
7599: my $filename=pop(@uriparts);
7600: my $pathname=join('/',@uriparts);
7601: return ($pathname,$filename);
7602: }
1.232 www 7603: # --------------------------------------------------- Is a resource on the map?
7604:
7605: sub is_on_map {
1.710 albertel 7606: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7607: #Trying to find the conditional for the file
1.620 albertel 7608: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7609: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7610: if ($match) {
1.289 bowersj2 7611: return (1,$1);
7612: } else {
1.434 www 7613: return (0,0);
1.289 bowersj2 7614: }
1.12 www 7615: }
7616:
1.427 www 7617: # --------------------------------------------------------- Get symb from alias
7618:
7619: sub get_symb_from_alias {
7620: my $symb=shift;
7621: my ($map,$resid,$url)=&decode_symb($symb);
7622: # Already is a symb
7623: if ($url) { return $symb; }
7624: # Must be an alias
7625: my $aliassymb='';
7626: my %bighash;
1.620 albertel 7627: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7628: &GDBM_READER(),0640)) {
7629: my $rid=$bighash{'mapalias_'.$symb};
7630: if ($rid) {
7631: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7632: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7633: $resid,$bighash{'src_'.$rid});
1.427 www 7634: }
7635: untie %bighash;
7636: }
7637: return $aliassymb;
7638: }
7639:
1.12 www 7640: # ----------------------------------------------------------------- Define Role
7641:
7642: sub definerole {
7643: if (allowed('mcr','/')) {
7644: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7645: foreach my $role (split(':',$sysrole)) {
7646: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7647: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7648: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7649: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7650: return "refused:s:$crole&$cqual";
7651: }
7652: }
1.191 harris41 7653: }
1.800 albertel 7654: foreach my $role (split(':',$domrole)) {
7655: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7656: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7657: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7658: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7659: return "refused:d:$crole&$cqual";
7660: }
7661: }
1.191 harris41 7662: }
1.800 albertel 7663: foreach my $role (split(':',$courole)) {
7664: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7665: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7666: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7667: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7668: return "refused:c:$crole&$cqual";
7669: }
7670: }
1.191 harris41 7671: }
1.620 albertel 7672: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7673: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7674: "rolesdef_$rolename=".
7675: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7676: return reply($command,$env{'user.home'});
1.12 www 7677: } else {
7678: return 'refused';
7679: }
1.105 harris41 7680: }
7681:
7682: # ---------------- Make a metadata query against the network of library servers
7683:
7684: sub metadata_query {
1.1172.2.33 raeburn 7685: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7686: my %rhash;
1.845 albertel 7687: my %libserv = &all_library();
1.244 matthew 7688: my @server_list = (defined($server_array) ? @$server_array
7689: : keys(%libserv) );
7690: for my $server (@server_list) {
1.1172.2.33 raeburn 7691: my $domains = '';
7692: if (ref($domains_hash) eq 'HASH') {
7693: $domains = $domains_hash->{$server};
7694: }
1.118 harris41 7695: unless ($custom or $customshow) {
1.1172.2.33 raeburn 7696: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7697: $rhash{$server}=$reply;
7698: }
7699: else {
7700: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 7701: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7702: $server);
7703: $rhash{$server}=$reply;
7704: }
1.112 harris41 7705: }
1.118 harris41 7706: return \%rhash;
1.240 www 7707: }
7708:
7709: # ----------------------------------------- Send log queries and wait for reply
7710:
7711: sub log_query {
7712: my ($uname,$udom,$query,%filters)=@_;
7713: my $uhome=&homeserver($uname,$udom);
7714: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7715: my $uhost=&hostname($uhome);
1.800 albertel 7716: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7717: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7718: $uhome);
1.479 albertel 7719: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7720: return get_query_reply($queryid);
7721: }
7722:
1.818 raeburn 7723: # -------------------------- Update MySQL table for portfolio file
7724:
7725: sub update_portfolio_table {
1.821 raeburn 7726: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7727: if ($group ne '') {
7728: $file_name =~s /^\Q$group\E//;
7729: }
1.818 raeburn 7730: my $homeserver = &homeserver($uname,$udom);
7731: my $queryid=
1.821 raeburn 7732: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7733: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7734: my $reply = &get_query_reply($queryid);
7735: return $reply;
7736: }
7737:
1.899 raeburn 7738: # -------------------------- Update MySQL allusers table
7739:
7740: sub update_allusers_table {
7741: my ($uname,$udom,$names) = @_;
7742: my $homeserver = &homeserver($uname,$udom);
7743: my $queryid=
7744: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7745: 'lastname='.&escape($names->{'lastname'}).'%%'.
7746: 'firstname='.&escape($names->{'firstname'}).'%%'.
7747: 'middlename='.&escape($names->{'middlename'}).'%%'.
7748: 'generation='.&escape($names->{'generation'}).'%%'.
7749: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7750: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7751: return;
1.899 raeburn 7752: }
7753:
1.508 raeburn 7754: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7755:
7756: sub fetch_enrollment_query {
1.511 raeburn 7757: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7758: my $homeserver;
1.547 raeburn 7759: my $maxtries = 1;
1.508 raeburn 7760: if ($context eq 'automated') {
7761: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7762: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7763: } else {
7764: $homeserver = &homeserver($cnum,$dom);
7765: }
1.838 albertel 7766: my $host=&hostname($homeserver);
1.506 raeburn 7767: my $cmd = '';
1.1000 raeburn 7768: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7769: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7770: }
7771: $cmd =~ s/%%$//;
7772: $cmd = &escape($cmd);
7773: my $query = 'fetchenrollment';
1.620 albertel 7774: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7775: unless ($queryid=~/^\Q$host\E\_/) {
7776: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7777: return 'error: '.$queryid;
7778: }
1.506 raeburn 7779: my $reply = &get_query_reply($queryid);
1.547 raeburn 7780: my $tries = 1;
7781: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7782: $reply = &get_query_reply($queryid);
7783: $tries ++;
7784: }
1.526 raeburn 7785: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7786: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7787: } else {
1.901 albertel 7788: my @responses = split(/:/,$reply);
1.515 raeburn 7789: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7790: foreach my $line (@responses) {
7791: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7792: $$replyref{$key} = $value;
7793: }
7794: } else {
1.1117 foxr 7795: my $pathname = LONCAPA::tempdir();
1.800 albertel 7796: foreach my $line (@responses) {
7797: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7798: $$replyref{$key} = $value;
7799: if ($value > 0) {
1.800 albertel 7800: foreach my $item (@{$$affiliatesref{$key}}) {
7801: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7802: my $destname = $pathname.'/'.$filename;
7803: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7804: if ($xml_classlist =~ /^error/) {
7805: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7806: } else {
1.506 raeburn 7807: if ( open(FILE,">$destname") ) {
7808: print FILE &unescape($xml_classlist);
7809: close(FILE);
1.526 raeburn 7810: } else {
7811: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7812: }
7813: }
7814: }
7815: }
7816: }
7817: }
7818: return 'ok';
7819: }
7820: return 'error';
7821: }
7822:
1.242 www 7823: sub get_query_reply {
7824: my $queryid=shift;
1.1117 foxr 7825: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7826: my $reply='';
7827: for (1..100) {
7828: sleep 2;
7829: if (-e $replyfile.'.end') {
1.448 albertel 7830: if (open(my $fh,$replyfile)) {
1.904 albertel 7831: $reply = join('',<$fh>);
7832: close($fh);
1.240 www 7833: } else { return 'error: reply_file_error'; }
1.242 www 7834: return &unescape($reply);
7835: }
1.240 www 7836: }
1.242 www 7837: return 'timeout:'.$queryid;
1.240 www 7838: }
7839:
7840: sub courselog_query {
1.241 www 7841: #
7842: # possible filters:
7843: # url: url or symb
7844: # username
7845: # domain
7846: # action: view, submit, grade
7847: # start: timestamp
7848: # end: timestamp
7849: #
1.240 www 7850: my (%filters)=@_;
1.620 albertel 7851: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7852: if ($filters{'url'}) {
7853: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7854: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7855: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7856: }
1.620 albertel 7857: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7858: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7859: return &log_query($cname,$cdom,'courselog',%filters);
7860: }
7861:
7862: sub userlog_query {
1.858 raeburn 7863: #
7864: # possible filters:
7865: # action: log check role
7866: # start: timestamp
7867: # end: timestamp
7868: #
1.240 www 7869: my ($uname,$udom,%filters)=@_;
7870: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7871: }
7872:
1.506 raeburn 7873: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7874:
7875: sub auto_run {
1.508 raeburn 7876: my ($cnum,$cdom) = @_;
1.876 raeburn 7877: my $response = 0;
7878: my $settings;
7879: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7880: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7881: $settings = $domconfig{'autoenroll'};
7882: if ($settings->{'run'} eq '1') {
7883: $response = 1;
7884: }
7885: } else {
1.934 raeburn 7886: my $homeserver;
7887: if (&is_course($cdom,$cnum)) {
7888: $homeserver = &homeserver($cnum,$cdom);
7889: } else {
7890: $homeserver = &domain($cdom,'primary');
7891: }
7892: if ($homeserver ne 'no_host') {
7893: $response = &reply('autorun:'.$cdom,$homeserver);
7894: }
1.876 raeburn 7895: }
1.506 raeburn 7896: return $response;
7897: }
1.776 albertel 7898:
1.506 raeburn 7899: sub auto_get_sections {
1.508 raeburn 7900: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7901: my $homeserver;
7902: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7903: $homeserver = &homeserver($cnum,$cdom);
7904: }
7905: if (!defined($homeserver)) {
7906: if ($cdom =~ /^$match_domain$/) {
7907: $homeserver = &domain($cdom,'primary');
7908: }
7909: }
7910: my @secs;
7911: if (defined($homeserver)) {
7912: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7913: unless ($response eq 'refused') {
7914: @secs = split(/:/,$response);
7915: }
1.506 raeburn 7916: }
7917: return @secs;
7918: }
1.776 albertel 7919:
1.506 raeburn 7920: sub auto_new_course {
1.1099 raeburn 7921: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7922: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7923: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7924: return $response;
7925: }
1.776 albertel 7926:
1.506 raeburn 7927: sub auto_validate_courseID {
1.508 raeburn 7928: my ($cnum,$cdom,$inst_course_id) = @_;
7929: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7930: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7931: return $response;
7932: }
1.776 albertel 7933:
1.1007 raeburn 7934: sub auto_validate_instcode {
1.1020 raeburn 7935: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7936: my ($homeserver,$response);
7937: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7938: $homeserver = &homeserver($cnum,$cdom);
7939: }
7940: if (!defined($homeserver)) {
7941: if ($cdom =~ /^$match_domain$/) {
7942: $homeserver = &domain($cdom,'primary');
7943: }
7944: }
1.1065 raeburn 7945: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7946: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 7947: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7948: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7949: }
7950:
1.506 raeburn 7951: sub auto_create_password {
1.873 raeburn 7952: my ($cnum,$cdom,$authparam,$udom) = @_;
7953: my ($homeserver,$response);
1.506 raeburn 7954: my $create_passwd = 0;
7955: my $authchk = '';
1.873 raeburn 7956: if ($udom =~ /^$match_domain$/) {
7957: $homeserver = &domain($udom,'primary');
7958: }
7959: if ($homeserver eq '') {
7960: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7961: $homeserver = &homeserver($cnum,$cdom);
7962: }
7963: }
7964: if ($homeserver eq '') {
7965: $authchk = 'nodomain';
1.506 raeburn 7966: } else {
1.873 raeburn 7967: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7968: if ($response eq 'refused') {
7969: $authchk = 'refused';
7970: } else {
1.901 albertel 7971: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7972: }
1.506 raeburn 7973: }
7974: return ($authparam,$create_passwd,$authchk);
7975: }
7976:
1.706 raeburn 7977: sub auto_photo_permission {
7978: my ($cnum,$cdom,$students) = @_;
7979: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7980: my ($outcome,$perm_reqd,$conditions) =
7981: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7982: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7983: return (undef,undef);
7984: }
1.706 raeburn 7985: return ($outcome,$perm_reqd,$conditions);
7986: }
7987:
7988: sub auto_checkphotos {
7989: my ($uname,$udom,$pid) = @_;
7990: my $homeserver = &homeserver($uname,$udom);
7991: my ($result,$resulttype);
7992: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7993: &escape($uname).':'.&escape($pid),
7994: $homeserver));
1.709 albertel 7995: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7996: return (undef,undef);
7997: }
1.706 raeburn 7998: if ($outcome) {
7999: ($result,$resulttype) = split(/:/,$outcome);
8000: }
8001: return ($result,$resulttype);
8002: }
8003:
8004: sub auto_photochoice {
8005: my ($cnum,$cdom) = @_;
8006: my $homeserver = &homeserver($cnum,$cdom);
8007: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8008: &escape($cdom),
8009: $homeserver)));
1.709 albertel 8010: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8011: return (undef,undef);
8012: }
1.706 raeburn 8013: return ($update,$comment);
8014: }
8015:
8016: sub auto_photoupdate {
8017: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8018: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8019: my $host=&hostname($homeserver);
1.706 raeburn 8020: my $cmd = '';
8021: my $maxtries = 1;
1.800 albertel 8022: foreach my $affiliate (keys(%{$affiliatesref})) {
8023: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8024: }
8025: $cmd =~ s/%%$//;
8026: $cmd = &escape($cmd);
8027: my $query = 'institutionalphotos';
8028: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8029: unless ($queryid=~/^\Q$host\E\_/) {
8030: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8031: return 'error: '.$queryid;
8032: }
8033: my $reply = &get_query_reply($queryid);
8034: my $tries = 1;
8035: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8036: $reply = &get_query_reply($queryid);
8037: $tries ++;
8038: }
8039: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8040: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8041: } else {
8042: my @responses = split(/:/,$reply);
8043: my $outcome = shift(@responses);
8044: foreach my $item (@responses) {
8045: my ($key,$value) = split(/=/,$item);
8046: $$photo{$key} = $value;
8047: }
8048: return $outcome;
8049: }
8050: return 'error';
8051: }
8052:
1.521 raeburn 8053: sub auto_instcode_format {
1.793 albertel 8054: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8055: $cat_order) = @_;
1.521 raeburn 8056: my $courses = '';
1.772 raeburn 8057: my @homeservers;
1.521 raeburn 8058: if ($caller eq 'global') {
1.841 albertel 8059: my %servers = &get_servers($codedom,'library');
8060: foreach my $tryserver (keys(%servers)) {
8061: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8062: push(@homeservers,$tryserver);
8063: }
1.584 raeburn 8064: }
1.1022 raeburn 8065: } elsif ($caller eq 'requests') {
8066: if ($codedom =~ /^$match_domain$/) {
8067: my $chome = &domain($codedom,'primary');
8068: unless ($chome eq 'no_host') {
8069: push(@homeservers,$chome);
8070: }
8071: }
1.521 raeburn 8072: } else {
1.772 raeburn 8073: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8074: }
1.793 albertel 8075: foreach my $code (keys(%{$instcodes})) {
8076: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8077: }
8078: chop($courses);
1.772 raeburn 8079: my $ok_response = 0;
8080: my $response;
8081: while (@homeservers > 0 && $ok_response == 0) {
8082: my $server = shift(@homeservers);
8083: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8084: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8085: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8086: split(/:/,$response);
1.772 raeburn 8087: %{$codes} = (%{$codes},&str2hash($codes_str));
8088: push(@{$codetitles},&str2array($codetitles_str));
8089: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8090: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8091: $ok_response = 1;
8092: }
8093: }
8094: if ($ok_response) {
1.521 raeburn 8095: return 'ok';
1.772 raeburn 8096: } else {
8097: return $response;
1.521 raeburn 8098: }
8099: }
8100:
1.792 raeburn 8101: sub auto_instcode_defaults {
8102: my ($domain,$returnhash,$code_order) = @_;
8103: my @homeservers;
1.841 albertel 8104:
8105: my %servers = &get_servers($domain,'library');
8106: foreach my $tryserver (keys(%servers)) {
8107: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8108: push(@homeservers,$tryserver);
8109: }
1.792 raeburn 8110: }
1.841 albertel 8111:
1.792 raeburn 8112: my $response;
1.841 albertel 8113: foreach my $server (@homeservers) {
1.792 raeburn 8114: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8115: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8116:
8117: foreach my $pair (split(/\&/,$response)) {
8118: my ($name,$value)=split(/\=/,$pair);
8119: if ($name eq 'code_order') {
8120: @{$code_order} = split(/\&/,&unescape($value));
8121: } else {
8122: $returnhash->{&unescape($name)}=&unescape($value);
8123: }
8124: }
8125: return 'ok';
1.792 raeburn 8126: }
1.841 albertel 8127:
8128: return $response;
1.1003 raeburn 8129: }
8130:
8131: sub auto_possible_instcodes {
1.1007 raeburn 8132: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8133: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8134: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8135: return;
8136: }
1.1003 raeburn 8137: my (@homeservers,$uhome);
8138: if (defined(&domain($domain,'primary'))) {
8139: $uhome=&domain($domain,'primary');
8140: push(@homeservers,&domain($domain,'primary'));
8141: } else {
8142: my %servers = &get_servers($domain,'library');
8143: foreach my $tryserver (keys(%servers)) {
8144: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8145: push(@homeservers,$tryserver);
8146: }
8147: }
8148: }
8149: my $response;
8150: foreach my $server (@homeservers) {
8151: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8152: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8153: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8154: split(':',$response);
8155: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8156: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8157: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8158: my ($name,$value)=split('=',$item);
8159: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8160: }
8161: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8162: my ($name,$value)=split('=',$item);
8163: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8164: }
8165: return 'ok';
8166: }
8167: return $response;
8168: }
1.792 raeburn 8169:
1.1010 raeburn 8170: sub auto_courserequest_checks {
8171: my ($dom) = @_;
1.1020 raeburn 8172: my ($homeserver,%validations);
8173: if ($dom =~ /^$match_domain$/) {
8174: $homeserver = &domain($dom,'primary');
8175: }
8176: unless ($homeserver eq 'no_host') {
8177: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8178: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8179: my @items = split(/&/,$response);
8180: foreach my $item (@items) {
8181: my ($key,$value) = split('=',$item);
8182: $validations{&unescape($key)} = &thaw_unescape($value);
8183: }
8184: }
8185: }
1.1010 raeburn 8186: return %validations;
8187: }
8188:
1.1020 raeburn 8189: sub auto_courserequest_validation {
1.1172.2.43 raeburn 8190: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8191: my ($homeserver,$response);
8192: if ($dom =~ /^$match_domain$/) {
8193: $homeserver = &domain($dom,'primary');
8194: }
1.1172.2.43 raeburn 8195: unless ($homeserver eq 'no_host') {
8196: my $customdata;
8197: if (ref($custominfo) eq 'HASH') {
8198: $customdata = &freeze_escape($custominfo);
8199: }
1.1020 raeburn 8200: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8201: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 8202: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8203: $customdata,$homeserver));
1.1020 raeburn 8204: }
8205: return $response;
8206: }
8207:
1.777 albertel 8208: sub auto_validate_class_sec {
1.918 raeburn 8209: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8210: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8211: my $ownerlist;
8212: if (ref($owners) eq 'ARRAY') {
8213: $ownerlist = join(',',@{$owners});
8214: } else {
8215: $ownerlist = $owners;
8216: }
1.773 raeburn 8217: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8218: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8219: return $response;
8220: }
8221:
1.1172.2.38 raeburn 8222: sub auto_crsreq_update {
8223: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 8224: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 8225: my ($homeserver,%crsreqresponse);
8226: if ($cdom =~ /^$match_domain$/) {
8227: $homeserver = &domain($cdom,'primary');
8228: }
8229: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8230: my $info;
8231: if (ref($inbound) eq 'HASH') {
8232: $info = &freeze_escape($inbound);
8233: }
8234: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8235: ':'.&escape($action).':'.&escape($ownername).':'.
8236: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 8237: &escape($title).':'.&escape($code).':'.
8238: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 8239: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8240: my @items = split(/&/,$response);
8241: foreach my $item (@items) {
8242: my ($key,$value) = split('=',$item);
8243: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8244: }
8245: }
8246: }
8247: return \%crsreqresponse;
8248: }
8249:
1.1172.2.78! raeburn 8250: sub auto_export_grades {
! 8251: my ($cdom,$cnum,$inforef,$gradesref) = @_;
! 8252: my ($homeserver,%exportresponse);
! 8253: if ($cdom =~ /^$match_domain$/) {
! 8254: $homeserver = &domain($cdom,'primary');
! 8255: }
! 8256: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
! 8257: my $info;
! 8258: if (ref($inforef) eq 'HASH') {
! 8259: $info = &freeze_escape($inforef);
! 8260: }
! 8261: if (ref($gradesref) eq 'HASH') {
! 8262: my $grades = &freeze_escape($gradesref);
! 8263: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
! 8264: $info.':'.$grades,$homeserver);
! 8265: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
! 8266: my @items = split(/&/,$response);
! 8267: foreach my $item (@items) {
! 8268: my ($key,$value) = split('=',$item);
! 8269: $exportresponse{&unescape($key)} = &thaw_unescape($value);
! 8270: }
! 8271: }
! 8272: }
! 8273: }
! 8274: return \%exportresponse;
! 8275: }
! 8276:
1.1172.2.68 raeburn 8277: sub check_instcode_cloning {
8278: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8279: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8280: return;
8281: }
8282: my $canclone;
8283: if (@{$code_order} > 0) {
8284: my $instcoderegexp ='^';
8285: my @clonecodes = split(/\&/,$cloner);
8286: foreach my $item (@{$code_order}) {
8287: if (grep(/^\Q$item\E=/,@clonecodes)) {
8288: foreach my $pair (@clonecodes) {
8289: my ($key,$val) = split(/\=/,$pair,2);
8290: $val = &unescape($val);
8291: if ($key eq $item) {
8292: $instcoderegexp .= '('.$val.')';
8293: last;
8294: }
8295: }
8296: } else {
8297: $instcoderegexp .= $codedefaults->{$item};
8298: }
8299: }
8300: $instcoderegexp .= '$';
8301: my (@from,@to);
8302: eval {
8303: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8304: (@to) = ($clonetocode =~ /$instcoderegexp/);
8305: };
8306: if ((@from > 0) && (@to > 0)) {
8307: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8308: if (!@diffs) {
8309: $canclone = 1;
8310: }
8311: }
8312: }
8313: return $canclone;
8314: }
8315:
8316: sub default_instcode_cloning {
8317: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8318: my (%codedefaults,@code_order,$canclone);
8319: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8320: %codedefaults = %{$codedefaultsref};
8321: @code_order = @{$codeorderref};
8322: } elsif ($clonedom) {
8323: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8324: }
8325: if (($domdefclone) && (@code_order)) {
8326: my @clonecodes = split(/\+/,$domdefclone);
8327: my $instcoderegexp ='^';
8328: foreach my $item (@code_order) {
8329: if (grep(/^\Q$item\E$/,@clonecodes)) {
8330: $instcoderegexp .= '('.$codedefaults{$item}.')';
8331: } else {
8332: $instcoderegexp .= $codedefaults{$item};
8333: }
8334: }
8335: $instcoderegexp .= '$';
8336: my (@from,@to);
8337: eval {
8338: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8339: (@to) = ($clonetocode =~ /$instcoderegexp/);
8340: };
8341: if ((@from > 0) && (@to > 0)) {
8342: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8343: if (!@diffs) {
8344: $canclone = 1;
8345: }
8346: }
8347: }
8348: return $canclone;
8349: }
8350:
1.679 raeburn 8351: # ------------------------------------------------------- Course Group routines
8352:
8353: sub get_coursegroups {
1.809 raeburn 8354: my ($cdom,$cnum,$group,$namespace) = @_;
8355: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8356: }
8357:
1.679 raeburn 8358: sub modify_coursegroup {
8359: my ($cdom,$cnum,$groupsettings) = @_;
8360: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8361: }
8362:
1.809 raeburn 8363: sub toggle_coursegroup_status {
8364: my ($cdom,$cnum,$group,$action) = @_;
8365: my ($from_namespace,$to_namespace);
8366: if ($action eq 'delete') {
8367: $from_namespace = 'coursegroups';
8368: $to_namespace = 'deleted_groups';
8369: } else {
8370: $from_namespace = 'deleted_groups';
8371: $to_namespace = 'coursegroups';
8372: }
8373: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8374: if (my $tmp = &error(%curr_group)) {
8375: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8376: return ('read error',$tmp);
8377: } else {
8378: my %savedsettings = %curr_group;
1.809 raeburn 8379: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8380: my $deloutcome;
8381: if ($result eq 'ok') {
1.809 raeburn 8382: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8383: } else {
8384: return ('write error',$result);
8385: }
8386: if ($deloutcome eq 'ok') {
8387: return 'ok';
8388: } else {
8389: return ('delete error',$deloutcome);
8390: }
8391: }
8392: }
8393:
1.679 raeburn 8394: sub modify_group_roles {
1.957 raeburn 8395: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8396: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8397: my $role = 'gr/'.&escape($userprivs);
8398: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8399: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8400: if ($result eq 'ok') {
8401: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8402: }
1.679 raeburn 8403: return $result;
8404: }
8405:
8406: sub modify_coursegroup_membership {
8407: my ($cdom,$cnum,$membership) = @_;
8408: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8409: return $result;
8410: }
8411:
1.682 raeburn 8412: sub get_active_groups {
8413: my ($udom,$uname,$cdom,$cnum) = @_;
8414: my $now = time;
8415: my %groups = ();
8416: foreach my $key (keys(%env)) {
1.811 albertel 8417: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8418: my ($start,$end) = split(/\./,$env{$key});
8419: if (($end!=0) && ($end<$now)) { next; }
8420: if (($start!=0) && ($start>$now)) { next; }
8421: if ($1 eq $cdom && $2 eq $cnum) {
8422: $groups{$3} = $env{$key} ;
8423: }
8424: }
8425: }
8426: return %groups;
8427: }
8428:
1.683 raeburn 8429: sub get_group_membership {
8430: my ($cdom,$cnum,$group) = @_;
8431: return(&dump('groupmembership',$cdom,$cnum,$group));
8432: }
8433:
8434: sub get_users_groups {
8435: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8436: my @usersgroups;
1.683 raeburn 8437: my $cachetime=1800;
8438:
8439: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8440: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8441: if (defined($cached)) {
1.734 albertel 8442: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8443: } else {
8444: $grouplist = '';
1.816 raeburn 8445: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8446: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8447: my $access_end = $env{'course.'.$courseid.
8448: '.default_enrollment_end_date'};
8449: my $now = time;
8450: foreach my $key (keys(%roleshash)) {
8451: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8452: my $group = $1;
8453: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8454: my $start = $2;
8455: my $end = $1;
8456: if ($start == -1) { next; } # deleted from group
8457: if (($start!=0) && ($start>$now)) { next; }
8458: if (($end!=0) && ($end<$now)) {
8459: if ($access_end && $access_end < $now) {
8460: if ($access_end - $end < 86400) {
8461: push(@usersgroups,$group);
1.733 raeburn 8462: }
8463: }
1.817 raeburn 8464: next;
1.733 raeburn 8465: }
1.817 raeburn 8466: push(@usersgroups,$group);
1.683 raeburn 8467: }
8468: }
8469: }
1.817 raeburn 8470: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8471: $grouplist = join(':',@usersgroups);
8472: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8473: }
1.733 raeburn 8474: return @usersgroups;
1.683 raeburn 8475: }
8476:
8477: sub devalidate_getgroups_cache {
8478: my ($udom,$uname,$cdom,$cnum)=@_;
8479: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8480:
1.683 raeburn 8481: my $hashid="$udom:$uname:$courseid";
8482: &devalidate_cache_new('getgroups',$hashid);
8483: }
8484:
1.12 www 8485: # ------------------------------------------------------------------ Plain Text
8486:
8487: sub plaintext {
1.988 raeburn 8488: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8489: if ($short =~ m{^cr/}) {
1.758 albertel 8490: return (split('/',$short))[-1];
8491: }
1.742 raeburn 8492: if (!defined($cid)) {
8493: $cid = $env{'request.course.id'};
8494: }
8495: my %rolenames = (
1.1008 raeburn 8496: Course => 'std',
8497: Community => 'alt1',
1.742 raeburn 8498: );
1.1037 raeburn 8499: if ($cid ne '') {
8500: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8501: unless ($forcedefault) {
8502: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8503: &Apache::lonlocal::mt_escape(\$roletext);
8504: return &Apache::lonlocal::mt($roletext);
8505: }
8506: }
8507: }
8508: if ((defined($type)) && (defined($rolenames{$type})) &&
8509: (defined($rolenames{$type})) &&
8510: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8511: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8512: } elsif ($cid ne '') {
8513: my $crstype = $env{'course.'.$cid.'.type'};
8514: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8515: (defined($prp{$short}{$rolenames{$crstype}}))) {
8516: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8517: }
1.742 raeburn 8518: }
1.1037 raeburn 8519: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8520: }
8521:
8522: # ----------------------------------------------------------------- Assign Role
8523:
8524: sub assignrole {
1.957 raeburn 8525: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8526: $context)=@_;
1.21 www 8527: my $mrole;
8528: if ($role =~ /^cr\//) {
1.393 www 8529: my $cwosec=$url;
1.811 albertel 8530: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8531: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8532: my $refused = 1;
8533: if ($context eq 'requestcourses') {
8534: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8535: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8536: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8537: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8538: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8539: if ($crsenv{'internal.courseowner'} eq
8540: $env{'user.name'}.':'.$env{'user.domain'}) {
8541: $refused = '';
8542: }
8543: }
8544: }
8545: }
8546: }
8547: if ($refused) {
8548: &logthis('Refused custom assignrole: '.
8549: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8550: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8551: return 'refused';
8552: }
1.104 www 8553: }
1.21 www 8554: $mrole='cr';
1.678 raeburn 8555: } elsif ($role =~ /^gr\//) {
8556: my $cwogrp=$url;
1.811 albertel 8557: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8558: unless (&allowed('mdg',$cwogrp)) {
8559: &logthis('Refused group assignrole: '.
8560: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8561: $env{'user.name'}.' at '.$env{'user.domain'});
8562: return 'refused';
8563: }
8564: $mrole='gr';
1.21 www 8565: } else {
1.82 www 8566: my $cwosec=$url;
1.811 albertel 8567: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8568: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8569: my $refused;
8570: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8571: if (!(&allowed('c'.$role,$url))) {
8572: $refused = 1;
8573: }
8574: } else {
8575: $refused = 1;
8576: }
1.947 raeburn 8577: if ($refused) {
1.1045 raeburn 8578: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8579: if (!$selfenroll && $context eq 'course') {
8580: my %crsenv;
8581: if ($role eq 'cc' || $role eq 'co') {
8582: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8583: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8584: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8585: if ($crsenv{'internal.courseowner'} eq
8586: $env{'user.name'}.':'.$env{'user.domain'}) {
8587: $refused = '';
8588: }
8589: }
8590: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8591: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8592: if ($crsenv{'internal.courseowner'} eq
8593: $env{'user.name'}.':'.$env{'user.domain'}) {
8594: $refused = '';
8595: }
8596: }
8597: }
8598: }
8599: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8600: $refused = '';
1.1017 raeburn 8601: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8602: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8603: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8604: my $wrongcc;
8605: if ($cnum =~ /^$match_community$/) {
8606: $wrongcc = 1 if ($role eq 'cc');
8607: } else {
8608: $wrongcc = 1 if ($role eq 'co');
8609: }
8610: unless ($wrongcc) {
8611: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8612: if ($crsenv{'internal.courseowner'} eq
8613: $env{'user.name'}.':'.$env{'user.domain'}) {
8614: $refused = '';
8615: }
1.1017 raeburn 8616: }
8617: }
1.1172.2.9 raeburn 8618: } elsif ($context eq 'requestauthor') {
8619: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8620: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8621: if ($env{'environment.requestauthor'} eq 'automatic') {
8622: $refused = '';
8623: } else {
8624: my %domdefaults = &get_domain_defaults($udom);
8625: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8626: my $checkbystatus;
8627: if ($env{'user.adv'}) {
8628: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8629: if ($disposition eq 'automatic') {
8630: $refused = '';
8631: } elsif ($disposition eq '') {
8632: $checkbystatus = 1;
8633: }
8634: } else {
8635: $checkbystatus = 1;
8636: }
8637: if ($checkbystatus) {
8638: if ($env{'environment.inststatus'}) {
8639: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8640: foreach my $type (@inststatuses) {
8641: if (($type ne '') &&
8642: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8643: $refused = '';
8644: }
8645: }
8646: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8647: $refused = '';
8648: }
8649: }
8650: }
8651: }
8652: }
1.1017 raeburn 8653: }
8654: if ($refused) {
1.947 raeburn 8655: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8656: ' '.$role.' '.$end.' '.$start.' by '.
8657: $env{'user.name'}.' at '.$env{'user.domain'});
8658: return 'refused';
8659: }
1.932 raeburn 8660: }
1.1131 raeburn 8661: } elsif ($role eq 'au') {
8662: if ($url ne '/'.$udom.'/') {
8663: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8664: ' to assign author role for '.$uname.':'.$udom.
8665: ' in domain: '.$url.' refused (wrong domain).');
8666: return 'refused';
8667: }
1.104 www 8668: }
1.21 www 8669: $mrole=$role;
8670: }
1.620 albertel 8671: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8672: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8673: if ($end) { $command.='_'.$end; }
1.21 www 8674: if ($start) {
8675: if ($end) {
1.81 www 8676: $command.='_'.$start;
1.21 www 8677: } else {
1.81 www 8678: $command.='_0_'.$start;
1.21 www 8679: }
8680: }
1.739 raeburn 8681: my $origstart = $start;
8682: my $origend = $end;
1.957 raeburn 8683: my $delflag;
1.357 www 8684: # actually delete
8685: if ($deleteflag) {
1.373 www 8686: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8687: # modify command to delete the role
1.620 albertel 8688: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8689: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8690: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8691: # set start and finish to negative values for userrolelog
8692: $start=-1;
8693: $end=-1;
1.957 raeburn 8694: $delflag = 1;
1.357 www 8695: }
8696: }
8697: # send command
1.349 www 8698: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8699: # log new user role if status is ok
1.349 www 8700: if ($answer eq 'ok') {
1.663 raeburn 8701: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 8702: if (($role eq 'cc') || ($role eq 'in') ||
8703: ($role eq 'ep') || ($role eq 'ad') ||
8704: ($role eq 'ta') || ($role eq 'st') ||
8705: ($role=~/^cr/) || ($role eq 'gr') ||
8706: ($role eq 'co')) {
1.1172.2.13 raeburn 8707: # for course roles, perform group memberships changes triggered by role change.
8708: unless ($role =~ /^gr/) {
8709: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8710: $origstart,$selfenroll,$context);
8711: }
1.1172.2.9 raeburn 8712: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8713: $selfenroll,$context);
8714: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8715: ($role eq 'au') || ($role eq 'dc')) {
8716: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8717: $context);
8718: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8719: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8720: $context);
8721: }
1.1053 raeburn 8722: if ($role eq 'cc') {
8723: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8724: }
1.349 www 8725: }
8726: return $answer;
1.169 harris41 8727: }
8728:
1.1053 raeburn 8729: sub autoupdate_coowners {
8730: my ($url,$end,$start,$uname,$udom) = @_;
8731: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8732: if (($cdom ne '') && ($cnum ne '')) {
8733: my $now = time;
8734: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8735: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8736: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8737: my $instcode = $coursehash{'internal.coursecode'};
8738: if ($instcode ne '') {
1.1056 raeburn 8739: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8740: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8741: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8742: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8743: if ($result eq 'valid') {
8744: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8745: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8746: push(@newcoowners,$coowner);
8747: }
8748: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8749: push(@newcoowners,$uname.':'.$udom);
8750: }
8751: @newcoowners = sort(@newcoowners);
8752: } else {
8753: push(@newcoowners,$uname.':'.$udom);
8754: }
8755: } else {
8756: if ($coursehash{'internal.co-owners'}) {
8757: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8758: unless ($coowner eq $uname.':'.$udom) {
8759: push(@newcoowners,$coowner);
8760: }
8761: }
8762: unless (@newcoowners > 0) {
8763: $delcoowners = 1;
8764: $coowners = '';
8765: }
8766: }
8767: }
8768: if (@newcoowners || $delcoowners) {
8769: &store_coowners($cdom,$cnum,$coursehash{'home'},
8770: $delcoowners,@newcoowners);
8771: }
8772: }
8773: }
8774: }
8775: }
8776: }
8777: }
8778:
8779: sub store_coowners {
8780: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8781: my $cid = $cdom.'_'.$cnum;
8782: my ($coowners,$delresult,$putresult);
8783: if (@newcoowners) {
8784: $coowners = join(',',@newcoowners);
8785: my %coownershash = (
8786: 'internal.co-owners' => $coowners,
8787: );
8788: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8789: if ($putresult eq 'ok') {
8790: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8791: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8792: }
8793: }
8794: }
8795: if ($delcoowners) {
8796: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8797: if ($delresult eq 'ok') {
8798: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8799: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8800: }
8801: }
8802: }
8803: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8804: my %crsinfo =
8805: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8806: if (ref($crsinfo{$cid}) eq 'HASH') {
8807: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8808: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8809: }
8810: }
8811: }
8812:
1.169 harris41 8813: # -------------------------------------------------- Modify user authentication
1.197 www 8814: # Overrides without validation
8815:
1.169 harris41 8816: sub modifyuserauth {
8817: my ($udom,$uname,$umode,$upass)=@_;
8818: my $uhome=&homeserver($uname,$udom);
1.197 www 8819: unless (&allowed('mau',$udom)) { return 'refused'; }
8820: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8821: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8822: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8823: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8824: &escape($upass),$uhome);
1.620 albertel 8825: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8826: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8827: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8828: &log($udom,,$uname,$uhome,
1.620 albertel 8829: 'Authentication changed by '.$env{'user.domain'}.', '.
8830: $env{'user.name'}.', '.$umode.
1.197 www 8831: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8832: unless ($reply eq 'ok') {
1.197 www 8833: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8834: return 'error: '.$reply;
8835: }
1.170 harris41 8836: return 'ok';
1.80 www 8837: }
8838:
1.81 www 8839: # --------------------------------------------------------------- Modify a user
1.80 www 8840:
1.81 www 8841: sub modifyuser {
1.206 matthew 8842: my ($udom, $uname, $uid,
8843: $umode, $upass, $first,
8844: $middle, $last, $gene,
1.1058 raeburn 8845: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8846: $udom= &LONCAPA::clean_domain($udom);
8847: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8848: my $showcandelete = 'none';
8849: if (ref($candelete) eq 'ARRAY') {
8850: if (@{$candelete} > 0) {
8851: $showcandelete = join(', ',@{$candelete});
8852: }
8853: }
1.81 www 8854: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8855: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8856: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8857: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8858: ' desiredhome not specified').
1.620 albertel 8859: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8860: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8861: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8862: my $newuser;
8863: if ($uhome eq 'no_host') {
8864: $newuser = 1;
8865: }
1.80 www 8866: # ----------------------------------------------------------------- Create User
1.406 albertel 8867: if (($uhome eq 'no_host') &&
8868: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8869: my $unhome='';
1.844 albertel 8870: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8871: $unhome = $desiredhome;
1.620 albertel 8872: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8873: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8874: } else { # load balancing routine for determining $unhome
1.81 www 8875: my $loadm=10000000;
1.841 albertel 8876: my %servers = &get_servers($udom,'library');
8877: foreach my $tryserver (keys(%servers)) {
8878: my $answer=reply('load',$tryserver);
8879: if (($answer=~/\d+/) && ($answer<$loadm)) {
8880: $loadm=$answer;
8881: $unhome=$tryserver;
8882: }
1.80 www 8883: }
8884: }
8885: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8886: return 'error: unable to find a home server for '.$uname.
8887: ' in domain '.$udom;
1.80 www 8888: }
8889: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8890: &escape($upass),$unhome);
8891: unless ($reply eq 'ok') {
8892: return 'error: '.$reply;
8893: }
1.230 stredwic 8894: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8895: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8896: return 'error: unable verify users home machine.';
1.80 www 8897: }
1.209 matthew 8898: } # End of creation of new user
1.80 www 8899: # ---------------------------------------------------------------------- Add ID
8900: if ($uid) {
8901: $uid=~tr/A-Z/a-z/;
8902: my %uidhash=&idrget($udom,$uname);
1.196 www 8903: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8904: && (!$forceid)) {
1.80 www 8905: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8906: return 'error: user id "'.$uid.'" does not match '.
8907: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8908: }
8909: } else {
8910: &idput($udom,($uname => $uid));
8911: }
8912: }
8913: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8914: my @tmp=&get('environment',
1.899 raeburn 8915: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8916: 'permanentemail','inststatus'],
1.134 albertel 8917: $udom,$uname);
1.1075 raeburn 8918: my (%names,%oldnames);
1.313 matthew 8919: if ($tmp[0] =~ m/^error:.*/) {
8920: %names=();
8921: } else {
8922: %names = @tmp;
1.1075 raeburn 8923: %oldnames = %names;
1.313 matthew 8924: }
1.388 www 8925: #
1.1058 raeburn 8926: # If name, email and/or uid are blank (e.g., because an uploaded file
8927: # of users did not contain them), do not overwrite existing values
8928: # unless field is in $candelete array ref.
8929: #
8930:
8931: my @fields = ('firstname','middlename','lastname','generation',
8932: 'permanentemail','id');
8933: my %newvalues;
8934: if (ref($candelete) eq 'ARRAY') {
8935: foreach my $field (@fields) {
8936: if (grep(/^\Q$field\E$/,@{$candelete})) {
8937: if ($field eq 'firstname') {
8938: $names{$field} = $first;
8939: } elsif ($field eq 'middlename') {
8940: $names{$field} = $middle;
8941: } elsif ($field eq 'lastname') {
8942: $names{$field} = $last;
8943: } elsif ($field eq 'generation') {
8944: $names{$field} = $gene;
8945: } elsif ($field eq 'permanentemail') {
8946: $names{$field} = $email;
8947: } elsif ($field eq 'id') {
8948: $names{$field} = $uid;
8949: }
8950: }
8951: }
8952: }
1.388 www 8953: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8954: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8955: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8956: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8957: if ($email) {
8958: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8959: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8960: }
1.899 raeburn 8961: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8962: if (defined($inststatus)) {
8963: $names{'inststatus'} = '';
8964: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8965: if (ref($usertypes) eq 'HASH') {
8966: my @okstatuses;
8967: foreach my $item (split(/:/,$inststatus)) {
8968: if (defined($usertypes->{$item})) {
8969: push(@okstatuses,$item);
8970: }
8971: }
8972: if (@okstatuses) {
8973: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8974: }
8975: }
8976: }
1.1075 raeburn 8977: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8978: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8979: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8980: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8981: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8982: } else {
8983: $logmsg .= ' during self creation';
8984: }
1.1075 raeburn 8985: my $changed;
8986: if ($newuser) {
8987: $changed = 1;
8988: } else {
8989: foreach my $field (@fields) {
8990: if ($names{$field} ne $oldnames{$field}) {
8991: $changed = 1;
8992: last;
8993: }
8994: }
8995: }
8996: unless ($changed) {
8997: $logmsg = 'No changes in user information needed for: '.$logmsg;
8998: &logthis($logmsg);
8999: return 'ok';
9000: }
9001: my $reply = &put('environment', \%names, $udom,$uname);
9002: if ($reply ne 'ok') {
9003: return 'error: '.$reply;
9004: }
1.1087 raeburn 9005: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9006: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9007: }
1.1075 raeburn 9008: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9009: &devalidate_cache_new('namescache',$uname.':'.$udom);
9010: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9011: &logthis($logmsg);
1.134 albertel 9012: return 'ok';
1.80 www 9013: }
9014:
1.81 www 9015: # -------------------------------------------------------------- Modify student
1.80 www 9016:
1.81 www 9017: sub modifystudent {
9018: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9019: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 9020: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 9021: if (!$cid) {
1.620 albertel 9022: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9023: return 'not_in_class';
9024: }
1.80 www 9025: }
9026: # --------------------------------------------------------------- Make the user
1.81 www 9027: my $reply=&modifyuser
1.209 matthew 9028: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9029: $desiredhome,$email,$inststatus);
1.80 www 9030: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9031: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 9032: # student's environment
1.297 matthew 9033: $uid = undef if (!$forceid);
1.455 albertel 9034: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 9035: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 9036: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 9037: return $reply;
9038: }
9039:
9040: sub modify_student_enrollment {
1.1172.2.23 raeburn 9041: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 9042: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 9043: my ($cdom,$cnum,$chome);
9044: if (!$cid) {
1.620 albertel 9045: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9046: return 'not_in_class';
9047: }
1.620 albertel 9048: $cdom=$env{'course.'.$cid.'.domain'};
9049: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9050: } else {
9051: ($cdom,$cnum)=split(/_/,$cid);
9052: }
1.620 albertel 9053: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9054: if (!$chome) {
1.457 raeburn 9055: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9056: }
1.455 albertel 9057: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9058: # Make sure the user exists
1.81 www 9059: my $uhome=&homeserver($uname,$udom);
9060: if (($uhome eq '') || ($uhome eq 'no_host')) {
9061: return 'error: no such user';
9062: }
1.297 matthew 9063: # Get student data if we were not given enough information
9064: if (!defined($first) || $first eq '' ||
9065: !defined($last) || $last eq '' ||
9066: !defined($uid) || $uid eq '' ||
9067: !defined($middle) || $middle eq '' ||
9068: !defined($gene) || $gene eq '') {
1.294 matthew 9069: # They did not supply us with enough data to enroll the student, so
9070: # we need to pick up more information.
1.297 matthew 9071: my %tmp = &get('environment',
1.294 matthew 9072: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9073: ,$udom,$uname);
9074:
1.800 albertel 9075: #foreach my $key (keys(%tmp)) {
9076: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9077: #}
1.294 matthew 9078: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9079: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9080: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9081: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9082: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9083: }
1.556 albertel 9084: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9085: my $user = "$uname:$udom";
9086: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9087: my $reply=cput('classlist',
1.1148 raeburn 9088: {$user =>
1.1172.2.76 raeburn 9089: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 9090: $cdom,$cnum);
1.1148 raeburn 9091: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9092: &devalidate_getsection_cache($udom,$uname,$cid);
9093: } else {
1.81 www 9094: return 'error: '.$reply;
9095: }
1.297 matthew 9096: # Add student role to user
1.83 www 9097: my $uurl='/'.$cid;
1.81 www 9098: $uurl=~s/\_/\//g;
9099: if ($usec) {
9100: $uurl.='/'.$usec;
9101: }
1.1148 raeburn 9102: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9103: $selfenroll,$context);
9104: if ($result ne 'ok') {
9105: if ($old_entry{$user} ne '') {
9106: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9107: } else {
9108: $reply = &del('classlist',[$user],$cdom,$cnum);
9109: }
9110: }
9111: return $result;
1.21 www 9112: }
9113:
1.556 albertel 9114: sub format_name {
9115: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9116: my $name;
9117: if ($first ne 'lastname') {
9118: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9119: } else {
9120: if ($lastname=~/\S/) {
9121: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9122: $name=~s/\s+,/,/;
9123: } else {
9124: $name.= $firstname.' '.$middlename.' '.$generation;
9125: }
9126: }
9127: $name=~s/^\s+//;
9128: $name=~s/\s+$//;
9129: $name=~s/\s+/ /g;
9130: return $name;
9131: }
9132:
1.84 www 9133: # ------------------------------------------------- Write to course preferences
9134:
9135: sub writecoursepref {
9136: my ($courseid,%prefs)=@_;
9137: $courseid=~s/^\///;
9138: $courseid=~s/\_/\//g;
9139: my ($cdomain,$cnum)=split(/\//,$courseid);
9140: my $chome=homeserver($cnum,$cdomain);
9141: if (($chome eq '') || ($chome eq 'no_host')) {
9142: return 'error: no such course';
9143: }
9144: my $cstring='';
1.800 albertel 9145: foreach my $pref (keys(%prefs)) {
9146: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9147: }
1.84 www 9148: $cstring=~s/\&$//;
9149: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9150: }
9151:
9152: # ---------------------------------------------------------- Make/modify course
9153:
9154: sub createcourse {
1.741 raeburn 9155: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9156: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9157: $url=&declutter($url);
9158: my $cid='';
1.1028 raeburn 9159: if ($context eq 'requestcourses') {
9160: my $can_create = 0;
9161: my ($ownername,$ownerdom) = split(':',$course_owner);
9162: if ($udom eq $ownerdom) {
9163: if (&usertools_access($ownername,$ownerdom,$category,undef,
9164: $context)) {
9165: $can_create = 1;
9166: }
9167: } else {
9168: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9169: $category);
9170: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9171: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9172: if (@curr > 0) {
9173: my @options = qw(approval validate autolimit);
9174: my $optregex = join('|',@options);
9175: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9176: $can_create = 1;
9177: }
9178: }
9179: }
9180: }
9181: if ($can_create) {
9182: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9183: unless (&allowed('ccc',$udom)) {
9184: return 'refused';
9185: }
1.1017 raeburn 9186: }
9187: } else {
9188: return 'refused';
9189: }
1.1028 raeburn 9190: } elsif (!&allowed('ccc',$udom)) {
9191: return 'refused';
1.84 www 9192: }
1.1011 raeburn 9193: # --------------------------------------------------------------- Get Unique ID
9194: my $uname;
9195: if ($cnum =~ /^$match_courseid$/) {
9196: my $chome=&homeserver($cnum,$udom,'true');
9197: if (($chome eq '') || ($chome eq 'no_host')) {
9198: $uname = $cnum;
9199: } else {
1.1038 raeburn 9200: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9201: }
9202: } else {
1.1038 raeburn 9203: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9204: }
9205: return $uname if ($uname =~ /^error/);
9206: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9207: if (!defined($course_server)) {
9208: if (defined(&domain($udom,'primary'))) {
9209: $course_server = &domain($udom,'primary');
9210: } else {
9211: $course_server = $env{'user.home'};
9212: }
9213: }
9214: my %host_servers =
9215: &Apache::lonnet::get_servers($udom,'library');
9216: unless ($host_servers{$course_server}) {
9217: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9218: }
1.84 www 9219: # ------------------------------------------------------------- Make the course
9220: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9221: $course_server);
1.84 www 9222: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9223: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9224: if (($uhome eq '') || ($uhome eq 'no_host')) {
9225: return 'error: no such course';
9226: }
1.271 www 9227: # ----------------------------------------------------------------- Course made
1.516 raeburn 9228: # log existence
1.1029 raeburn 9229: my $now = time;
1.918 raeburn 9230: my $newcourse = {
9231: $udom.'_'.$uname => {
1.921 raeburn 9232: description => $description,
9233: inst_code => $inst_code,
9234: owner => $course_owner,
9235: type => $crstype,
1.1029 raeburn 9236: creator => $env{'user.name'}.':'.
9237: $env{'user.domain'},
9238: created => $now,
9239: context => $context,
1.918 raeburn 9240: },
9241: };
1.921 raeburn 9242: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9243: # set toplevel url
1.271 www 9244: my $topurl=$url;
9245: unless ($nonstandard) {
9246: # ------------------------------------------ For standard courses, make top url
9247: my $mapurl=&clutter($url);
1.278 www 9248: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9249: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9250: <map>
9251: <resource id="1" type="start"></resource>
9252: <resource id="2" src="$mapurl"></resource>
9253: <resource id="3" type="finish"></resource>
9254: <link index="1" from="1" to="2"></link>
9255: <link index="2" from="2" to="3"></link>
9256: </map>
9257: ENDINITMAP
9258: $topurl=&declutter(
1.638 albertel 9259: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9260: );
9261: }
9262: # ----------------------------------------------------------- Write preferences
1.84 www 9263: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9264: ('description' => $description,
9265: 'url' => $topurl,
9266: 'internal.creator' => $env{'user.name'}.':'.
9267: $env{'user.domain'},
9268: 'internal.created' => $now,
9269: 'internal.creationcontext' => $context)
9270: );
1.84 www 9271: return '/'.$udom.'/'.$uname;
9272: }
9273:
1.1011 raeburn 9274: # ------------------------------------------------------------------- Create ID
9275: sub generate_coursenum {
1.1038 raeburn 9276: my ($udom,$crstype) = @_;
1.1011 raeburn 9277: my $domdesc = &domain($udom);
9278: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9279: my $first;
9280: if ($crstype eq 'Community') {
9281: $first = '0';
9282: } else {
9283: $first = int(1+rand(9));
9284: }
9285: my $uname=$first.
1.1011 raeburn 9286: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9287: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9288: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9289: # ----------------------------------------------- Make sure that does not exist
9290: my $uhome=&homeserver($uname,$udom,'true');
9291: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9292: if ($crstype eq 'Community') {
9293: $first = '0';
9294: } else {
9295: $first = int(1+rand(9));
9296: }
9297: $uname=$first.
1.1011 raeburn 9298: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9299: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9300: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9301: $uhome=&homeserver($uname,$udom,'true');
9302: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9303: return 'error: unable to generate unique course-ID';
9304: }
9305: }
9306: return $uname;
9307: }
9308:
1.813 albertel 9309: sub is_course {
1.1167 droeschl 9310: my ($cdom, $cnum) = scalar(@_) == 1 ?
9311: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9312:
9313: return unless $cdom and $cnum;
9314:
9315: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9316: '.');
9317:
1.1172.2.23 raeburn 9318: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9319: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9320: }
9321:
1.1015 raeburn 9322: sub store_userdata {
9323: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9324: my $result;
1.1016 raeburn 9325: if ($datakey ne '') {
1.1013 raeburn 9326: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9327: if ($udom eq '' || $uname eq '') {
9328: $udom = $env{'user.domain'};
9329: $uname = $env{'user.name'};
9330: }
9331: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9332: if (($uhome eq '') || ($uhome eq 'no_host')) {
9333: $result = 'error: no_host';
9334: } else {
9335: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9336: $storehash->{'host'} = $perlvar{'lonHostID'};
9337:
9338: my $namevalue='';
9339: foreach my $key (keys(%{$storehash})) {
9340: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9341: }
9342: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 9343: unless ($namespace eq 'courserequests') {
9344: $datakey = &escape($datakey);
9345: }
1.1105 raeburn 9346: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9347: $namevalue,$uhome);
1.1013 raeburn 9348: }
9349: } else {
9350: $result = 'error: data to store was not a hash reference';
9351: }
9352: } else {
9353: $result= 'error: invalid requestkey';
9354: }
9355: return $result;
9356: }
9357:
1.21 www 9358: # ---------------------------------------------------------- Assign Custom Role
9359:
9360: sub assigncustomrole {
1.957 raeburn 9361: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9362: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9363: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9364: }
9365:
9366: # ----------------------------------------------------------------- Revoke Role
9367:
9368: sub revokerole {
1.957 raeburn 9369: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9370: my $now=time;
1.965 raeburn 9371: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9372: }
9373:
9374: # ---------------------------------------------------------- Revoke Custom Role
9375:
9376: sub revokecustomrole {
1.957 raeburn 9377: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9378: my $now=time;
1.357 www 9379: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9380: $deleteflag,$selfenroll,$context);
1.17 www 9381: }
9382:
1.533 banghart 9383: # ------------------------------------------------------------ Disk usage
1.535 albertel 9384: sub diskusage {
1.955 raeburn 9385: my ($udom,$uname,$directorypath,$getpropath)=@_;
9386: $directorypath =~ s/\/$//;
9387: my $listing=&reply('du2:'.&escape($directorypath).':'
9388: .&escape($getpropath).':'.&escape($uname).':'
9389: .&escape($udom),homeserver($uname,$udom));
9390: if ($listing eq 'unknown_cmd') {
9391: if ($getpropath) {
9392: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9393: }
9394: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9395: }
1.514 albertel 9396: return $listing;
1.512 banghart 9397: }
9398:
1.566 banghart 9399: sub is_locked {
1.1096 raeburn 9400: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9401: my @check;
9402: my $is_locked;
1.1093 raeburn 9403: push (@check,$file_name);
1.613 albertel 9404: my %locked = &get('file_permissions',\@check,
1.620 albertel 9405: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9406: my ($tmp)=keys(%locked);
9407: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9408:
1.566 banghart 9409: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9410: $is_locked = 'false';
9411: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9412: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9413: $is_locked = 'true';
1.1096 raeburn 9414: if (ref($which) eq 'ARRAY') {
9415: push(@{$which},$entry);
9416: } else {
9417: last;
9418: }
1.745 raeburn 9419: }
9420: }
1.566 banghart 9421: } else {
9422: $is_locked = 'false';
9423: }
1.1093 raeburn 9424: return $is_locked;
1.566 banghart 9425: }
9426:
1.759 albertel 9427: sub declutter_portfile {
9428: my ($file) = @_;
1.833 albertel 9429: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9430: return $file;
9431: }
9432:
1.559 banghart 9433: # ------------------------------------------------------------- Mark as Read Only
9434:
9435: sub mark_as_readonly {
9436: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9437: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9438: my ($tmp)=keys(%current_permissions);
9439: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9440: foreach my $file (@{$files}) {
1.759 albertel 9441: $file = &declutter_portfile($file);
1.561 banghart 9442: push(@{$current_permissions{$file}},$what);
1.559 banghart 9443: }
1.613 albertel 9444: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9445: return;
9446: }
9447:
1.572 banghart 9448: # ------------------------------------------------------------Save Selected Files
9449:
9450: sub save_selected_files {
9451: my ($user, $path, @files) = @_;
9452: my $filename = $user."savedfiles";
1.573 banghart 9453: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9454: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9455: foreach my $file (@files) {
1.620 albertel 9456: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9457: }
9458: foreach my $file (@other_files) {
1.574 banghart 9459: print (OUT $file."\n");
1.572 banghart 9460: }
1.574 banghart 9461: close (OUT);
1.572 banghart 9462: return 'ok';
9463: }
9464:
1.574 banghart 9465: sub clear_selected_files {
9466: my ($user) = @_;
9467: my $filename = $user."savedfiles";
1.1117 foxr 9468: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9469: print (OUT undef);
9470: close (OUT);
9471: return ("ok");
9472: }
9473:
1.572 banghart 9474: sub files_in_path {
9475: my ($user, $path) = @_;
9476: my $filename = $user."savedfiles";
9477: my %return_files;
1.1117 foxr 9478: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9479: while (my $line_in = <IN>) {
1.574 banghart 9480: chomp ($line_in);
9481: my @paths_and_file = split (m!/!, $line_in);
9482: my $file_part = pop (@paths_and_file);
9483: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9484: $path_part.='/';
9485: my $path_and_file = $path_part.$file_part;
9486: if ($path_part eq $path) {
9487: $return_files{$file_part}= 'selected';
9488: }
9489: }
1.574 banghart 9490: close (IN);
9491: return (\%return_files);
1.572 banghart 9492: }
9493:
9494: # called in portfolio select mode, to show files selected NOT in current directory
9495: sub files_not_in_path {
9496: my ($user, $path) = @_;
9497: my $filename = $user."savedfiles";
9498: my @return_files;
9499: my $path_part;
1.1117 foxr 9500: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9501: while (my $line = <IN>) {
1.572 banghart 9502: #ok, I know it's clunky, but I want it to work
1.800 albertel 9503: my @paths_and_file = split(m|/|, $line);
9504: my $file_part = pop(@paths_and_file);
9505: chomp($file_part);
9506: my $path_part = join('/', @paths_and_file);
1.572 banghart 9507: $path_part .= '/';
9508: my $path_and_file = $path_part.$file_part;
9509: if ($path_part ne $path) {
1.800 albertel 9510: push(@return_files, ($path_and_file));
1.572 banghart 9511: }
9512: }
1.800 albertel 9513: close(OUT);
1.574 banghart 9514: return (@return_files);
1.572 banghart 9515: }
9516:
1.745 raeburn 9517: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9518:
1.745 raeburn 9519: sub get_portfile_permissions {
9520: my ($domain,$user) = @_;
1.613 albertel 9521: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9522: my ($tmp)=keys(%current_permissions);
9523: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9524: return \%current_permissions;
9525: }
9526:
9527: #---------------------------------------------Get portfolio file access controls
9528:
1.749 raeburn 9529: sub get_access_controls {
1.745 raeburn 9530: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9531: my %access;
9532: my $real_file = $file;
9533: $file =~ s/\.meta$//;
1.745 raeburn 9534: if (defined($file)) {
1.749 raeburn 9535: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9536: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9537: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9538: }
9539: }
1.745 raeburn 9540: } else {
1.749 raeburn 9541: foreach my $key (keys(%{$current_permissions})) {
9542: if ($key =~ /\0accesscontrol$/) {
9543: if (defined($group)) {
9544: if ($key !~ m-^\Q$group\E/-) {
9545: next;
9546: }
9547: }
9548: my ($fullpath) = split(/\0/,$key);
9549: if (ref($$current_permissions{$key}) eq 'HASH') {
9550: foreach my $control (keys(%{$$current_permissions{$key}})) {
9551: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9552: }
9553: }
9554: }
9555: }
9556: }
9557: return %access;
9558: }
9559:
9560: sub modify_access_controls {
9561: my ($file_name,$changes,$domain,$user)=@_;
9562: my ($outcome,$deloutcome);
9563: my %store_permissions;
9564: my %new_values;
9565: my %new_control;
9566: my %translation;
9567: my @deletions = ();
9568: my $now = time;
9569: if (exists($$changes{'activate'})) {
9570: if (ref($$changes{'activate'}) eq 'HASH') {
9571: my @newitems = sort(keys(%{$$changes{'activate'}}));
9572: my $numnew = scalar(@newitems);
9573: for (my $i=0; $i<$numnew; $i++) {
9574: my $newkey = $newitems[$i];
9575: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9576: if ($newkey =~ /^\d+:/) {
9577: $newkey =~ s/^(\d+)/$newid/;
9578: $translation{$1} = $newid;
9579: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9580: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9581: $translation{$1} = $newid;
9582: }
1.749 raeburn 9583: $new_values{$file_name."\0".$newkey} =
9584: $$changes{'activate'}{$newitems[$i]};
9585: $new_control{$newkey} = $now;
9586: }
9587: }
9588: }
9589: my %todelete;
9590: my %changed_items;
9591: foreach my $action ('delete','update') {
9592: if (exists($$changes{$action})) {
9593: if (ref($$changes{$action}) eq 'HASH') {
9594: foreach my $key (keys(%{$$changes{$action}})) {
9595: my ($itemnum) = ($key =~ /^([^:]+):/);
9596: if ($action eq 'delete') {
9597: $todelete{$itemnum} = 1;
9598: } else {
9599: $changed_items{$itemnum} = $key;
9600: }
9601: }
1.745 raeburn 9602: }
9603: }
1.749 raeburn 9604: }
9605: # get lock on access controls for file.
9606: my $lockhash = {
9607: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9608: ':'.$env{'user.domain'},
9609: };
9610: my $tries = 0;
9611: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9612:
9613: while (($gotlock ne 'ok') && $tries <3) {
9614: $tries ++;
9615: sleep 1;
9616: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9617: }
9618: if ($gotlock eq 'ok') {
9619: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9620: my ($tmp)=keys(%curr_permissions);
9621: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9622: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9623: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9624: if (ref($curr_controls) eq 'HASH') {
9625: foreach my $control_item (keys(%{$curr_controls})) {
9626: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9627: if (defined($todelete{$itemnum})) {
9628: push(@deletions,$file_name."\0".$control_item);
9629: } else {
9630: if (defined($changed_items{$itemnum})) {
9631: $new_control{$changed_items{$itemnum}} = $now;
9632: push(@deletions,$file_name."\0".$control_item);
9633: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9634: } else {
9635: $new_control{$control_item} = $$curr_controls{$control_item};
9636: }
9637: }
1.745 raeburn 9638: }
9639: }
9640: }
1.970 raeburn 9641: my ($group);
9642: if (&is_course($domain,$user)) {
9643: ($group,my $file) = split(/\//,$file_name,2);
9644: }
1.749 raeburn 9645: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9646: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9647: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9648: # remove lock
9649: my @del_lock = ($file_name."\0".'locked_access_records');
9650: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9651: my $sqlresult =
1.970 raeburn 9652: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9653: $group);
1.749 raeburn 9654: } else {
9655: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9656: }
1.749 raeburn 9657: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9658: }
9659:
1.827 raeburn 9660: sub make_public_indefinitely {
9661: my ($requrl) = @_;
9662: my $now = time;
9663: my $action = 'activate';
9664: my $aclnum = 0;
9665: if (&is_portfolio_url($requrl)) {
9666: my (undef,$udom,$unum,$file_name,$group) =
9667: &parse_portfolio_url($requrl);
9668: my $current_perms = &get_portfile_permissions($udom,$unum);
9669: my %access_controls = &get_access_controls($current_perms,
9670: $group,$file_name);
9671: foreach my $key (keys(%{$access_controls{$file_name}})) {
9672: my ($num,$scope,$end,$start) =
9673: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9674: if ($scope eq 'public') {
9675: if ($start <= $now && $end == 0) {
9676: $action = 'none';
9677: } else {
9678: $action = 'update';
9679: $aclnum = $num;
9680: }
9681: last;
9682: }
9683: }
9684: if ($action eq 'none') {
9685: return 'ok';
9686: } else {
9687: my %changes;
9688: my $newend = 0;
9689: my $newstart = $now;
9690: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9691: $changes{$action}{$newkey} = {
9692: type => 'public',
9693: time => {
9694: start => $newstart,
9695: end => $newend,
9696: },
9697: };
9698: my ($outcome,$deloutcome,$new_values,$translation) =
9699: &modify_access_controls($file_name,\%changes,$udom,$unum);
9700: return $outcome;
9701: }
9702: } else {
9703: return 'invalid';
9704: }
9705: }
9706:
1.745 raeburn 9707: #------------------------------------------------------Get Marked as Read Only
9708:
9709: sub get_marked_as_readonly {
9710: my ($domain,$user,$what,$group) = @_;
9711: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9712: my @readonly_files;
1.629 banghart 9713: my $cmp1=$what;
9714: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9715: while (my ($file_name,$value) = each(%{$current_permissions})) {
9716: if (defined($group)) {
9717: if ($file_name !~ m-^\Q$group\E/-) {
9718: next;
9719: }
9720: }
1.561 banghart 9721: if (ref($value) eq "ARRAY"){
9722: foreach my $stored_what (@{$value}) {
1.629 banghart 9723: my $cmp2=$stored_what;
1.759 albertel 9724: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9725: $cmp2=join('',@{$stored_what});
1.745 raeburn 9726: }
1.629 banghart 9727: if ($cmp1 eq $cmp2) {
1.561 banghart 9728: push(@readonly_files, $file_name);
1.745 raeburn 9729: last;
1.563 banghart 9730: } elsif (!defined($what)) {
9731: push(@readonly_files, $file_name);
1.745 raeburn 9732: last;
1.561 banghart 9733: }
9734: }
1.745 raeburn 9735: }
1.561 banghart 9736: }
9737: return @readonly_files;
9738: }
1.577 banghart 9739: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9740:
1.577 banghart 9741: sub get_marked_as_readonly_hash {
1.745 raeburn 9742: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9743: my %readonly_files;
1.745 raeburn 9744: while (my ($file_name,$value) = each(%{$current_permissions})) {
9745: if (defined($group)) {
9746: if ($file_name !~ m-^\Q$group\E/-) {
9747: next;
9748: }
9749: }
1.577 banghart 9750: if (ref($value) eq "ARRAY"){
9751: foreach my $stored_what (@{$value}) {
1.745 raeburn 9752: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9753: foreach my $lock_descriptor(@{$stored_what}) {
9754: if ($lock_descriptor eq 'graded') {
9755: $readonly_files{$file_name} = 'graded';
9756: } elsif ($lock_descriptor eq 'handback') {
9757: $readonly_files{$file_name} = 'handback';
9758: } else {
9759: if (!exists($readonly_files{$file_name})) {
9760: $readonly_files{$file_name} = 'locked';
9761: }
9762: }
1.745 raeburn 9763: }
1.750 banghart 9764: }
1.577 banghart 9765: }
9766: }
9767: }
9768: return %readonly_files;
9769: }
1.559 banghart 9770: # ------------------------------------------------------------ Unmark as Read Only
9771:
9772: sub unmark_as_readonly {
1.629 banghart 9773: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9774: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9775: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9776: $file_name = &declutter_portfile($file_name);
1.634 albertel 9777: my $symb_crs = $what;
9778: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9779: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9780: my ($tmp)=keys(%current_permissions);
9781: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9782: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9783: foreach my $file (@readonly_files) {
1.759 albertel 9784: my $clean_file = &declutter_portfile($file);
9785: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9786: my $current_locks = $current_permissions{$file};
1.563 banghart 9787: my @new_locks;
9788: my @del_keys;
9789: if (ref($current_locks) eq "ARRAY"){
9790: foreach my $locker (@{$current_locks}) {
1.632 albertel 9791: my $compare=$locker;
1.749 raeburn 9792: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9793: $compare=join('',@{$locker});
1.746 raeburn 9794: if ($compare ne $symb_crs) {
9795: push(@new_locks, $locker);
9796: }
1.563 banghart 9797: }
9798: }
1.650 albertel 9799: if (scalar(@new_locks) > 0) {
1.563 banghart 9800: $current_permissions{$file} = \@new_locks;
9801: } else {
9802: push(@del_keys, $file);
1.613 albertel 9803: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9804: delete($current_permissions{$file});
1.563 banghart 9805: }
9806: }
1.561 banghart 9807: }
1.613 albertel 9808: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9809: return;
9810: }
1.512 banghart 9811:
1.17 www 9812: # ------------------------------------------------------------ Directory lister
9813:
9814: sub dirlist {
1.955 raeburn 9815: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9816: $uri=~s/^\///;
9817: $uri=~s/\/$//;
1.253 stredwic 9818: my ($udom, $uname);
1.955 raeburn 9819: if ($getuserdir) {
1.253 stredwic 9820: $udom = $userdomain;
9821: $uname = $username;
1.955 raeburn 9822: } else {
9823: (undef,$udom,$uname)=split(/\//,$uri);
9824: if(defined($userdomain)) {
9825: $udom = $userdomain;
9826: }
9827: if(defined($username)) {
9828: $uname = $username;
9829: }
1.253 stredwic 9830: }
1.955 raeburn 9831: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9832:
1.955 raeburn 9833: $dirRoot = $perlvar{'lonDocRoot'};
9834: if (defined($getpropath)) {
9835: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9836: $dirRoot =~ s/\/$//;
1.955 raeburn 9837: } elsif (defined($getuserdir)) {
9838: my $subdir=$uname.'__';
9839: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9840: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9841: ."/$udom/$subdir/$uname";
9842: } elsif (defined($alternateRoot)) {
9843: $dirRoot = $alternateRoot;
1.751 banghart 9844: }
1.253 stredwic 9845:
9846: if($udom) {
9847: if($uname) {
1.1135 raeburn 9848: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9849: if ($uhome eq 'no_host') {
9850: return ([],'no_host');
9851: }
1.955 raeburn 9852: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9853: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9854: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9855: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9856: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9857: } else {
9858: @listing_results = map { &unescape($_); } split(/:/,$listing);
9859: }
1.605 matthew 9860: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9861: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9862: @listing_results = split(/:/,$listing);
9863: } else {
9864: @listing_results = map { &unescape($_); } split(/:/,$listing);
9865: }
1.1135 raeburn 9866: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9867: ($listing eq 'rejected') || ($listing eq 'refused') ||
9868: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9869: return ([],$listing);
9870: } else {
9871: return (\@listing_results);
1.1135 raeburn 9872: }
1.955 raeburn 9873: } elsif(!$alternateRoot) {
1.1136 raeburn 9874: my (%allusers,%listerror);
1.841 albertel 9875: my %servers = &get_servers($udom,'library');
1.955 raeburn 9876: foreach my $tryserver (keys(%servers)) {
9877: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9878: &escape($udom),$tryserver);
9879: if ($listing eq 'unknown_cmd') {
9880: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9881: $udom, $tryserver);
9882: } else {
9883: @listing_results = map { &unescape($_); } split(/:/,$listing);
9884: }
1.841 albertel 9885: if ($listing eq 'unknown_cmd') {
9886: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9887: $udom, $tryserver);
9888: @listing_results = split(/:/,$listing);
9889: } else {
9890: @listing_results =
9891: map { &unescape($_); } split(/:/,$listing);
9892: }
1.1136 raeburn 9893: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9894: ($listing eq 'rejected') || ($listing eq 'refused') ||
9895: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9896: $listerror{$tryserver} = $listing;
9897: } else {
1.841 albertel 9898: foreach my $line (@listing_results) {
9899: my ($entry) = split(/&/,$line,2);
9900: $allusers{$entry} = 1;
9901: }
9902: }
1.253 stredwic 9903: }
1.1136 raeburn 9904: my @alluserslist=();
1.800 albertel 9905: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9906: push(@alluserslist,$user.'&user');
1.253 stredwic 9907: }
1.1136 raeburn 9908: return (\@alluserslist);
1.253 stredwic 9909: } else {
1.1136 raeburn 9910: return ([],'missing username');
1.253 stredwic 9911: }
1.955 raeburn 9912: } elsif(!defined($getpropath)) {
1.1136 raeburn 9913: my $path = $perlvar{'lonDocRoot'}.'/res/';
9914: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9915: return (\@all_domains);
1.955 raeburn 9916: } else {
1.1136 raeburn 9917: return ([],'missing domain');
1.275 stredwic 9918: }
9919: }
9920:
9921: # --------------------------------------------- GetFileTimestamp
9922: # This function utilizes dirlist and returns the date stamp for
9923: # when it was last modified. It will also return an error of -1
9924: # if an error occurs
9925:
9926: sub GetFileTimestamp {
1.955 raeburn 9927: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9928: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9929: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9930: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9931: undef,$getuserdir);
9932: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9933: return -1;
9934: }
9935: if (ref($fileref) eq 'ARRAY') {
9936: my @stats = split('&',$fileref->[0]);
1.375 matthew 9937: # @stats contains first the filename, then the stat output
9938: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9939: } else {
9940: return -1;
1.253 stredwic 9941: }
1.26 www 9942: }
9943:
1.712 albertel 9944: sub stat_file {
9945: my ($uri) = @_;
1.787 albertel 9946: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9947:
1.955 raeburn 9948: my ($udom,$uname,$file);
1.712 albertel 9949: if ($uri =~ m-^/(uploaded|editupload)/-) {
9950: ($udom,$uname,$file) =
1.811 albertel 9951: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9952: $file = 'userfiles/'.$file;
9953: }
9954: if ($uri =~ m-^/res/-) {
9955: ($udom,$uname) =
1.807 albertel 9956: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9957: $file = $uri;
9958: }
9959:
9960: if (!$udom || !$uname || !$file) {
9961: # unable to handle the uri
9962: return ();
9963: }
1.956 raeburn 9964: my $getpropath;
9965: if ($file =~ /^userfiles\//) {
9966: $getpropath = 1;
9967: }
1.1136 raeburn 9968: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9969: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9970: return ();
9971: } else {
9972: if (ref($listref) eq 'ARRAY') {
9973: my @stats = split('&',$listref->[0]);
9974: shift(@stats); #filename is first
9975: return @stats;
9976: }
1.712 albertel 9977: }
9978: return ();
9979: }
9980:
1.26 www 9981: # -------------------------------------------------------- Value of a Condition
9982:
1.713 albertel 9983: # gets the value of a specific preevaluated condition
9984: # stored in the string $env{user.state.<cid>}
9985: # or looks up a condition reference in the bighash and if if hasn't
9986: # already been evaluated recurses into docondval to get the value of
9987: # the condition, then memoizing it to
9988: # $env{user.state.<cid>.<condition>}
1.40 www 9989: sub directcondval {
9990: my $number=shift;
1.620 albertel 9991: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9992: &Apache::lonuserstate::evalstate();
9993: }
1.713 albertel 9994: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9995: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9996: } elsif ($number =~ /^_/) {
9997: my $sub_condition;
9998: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9999: &GDBM_READER(),0640)) {
10000: $sub_condition=$bighash{'conditions'.$number};
10001: untie(%bighash);
10002: }
10003: my $value = &docondval($sub_condition);
1.949 raeburn 10004: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10005: return $value;
10006: }
1.620 albertel 10007: if ($env{'user.state.'.$env{'request.course.id'}}) {
10008: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10009: } else {
10010: return 2;
10011: }
10012: }
10013:
1.713 albertel 10014: # get the collection of conditions for this resource
1.26 www 10015: sub condval {
10016: my $condidx=shift;
1.54 www 10017: my $allpathcond='';
1.713 albertel 10018: foreach my $cond (split(/\|/,$condidx)) {
10019: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10020: $allpathcond.=
10021: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10022: }
1.191 harris41 10023: }
1.54 www 10024: $allpathcond=~s/\|$//;
1.713 albertel 10025: return &docondval($allpathcond);
10026: }
10027:
10028: #evaluates an expression of conditions
10029: sub docondval {
10030: my ($allpathcond) = @_;
10031: my $result=0;
10032: if ($env{'request.course.id'}
10033: && defined($allpathcond)) {
10034: my $operand='|';
10035: my @stack;
10036: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10037: if ($chunk eq '(') {
10038: push @stack,($operand,$result);
10039: } elsif ($chunk eq ')') {
10040: my $before=pop @stack;
10041: if (pop @stack eq '&') {
10042: $result=$result>$before?$before:$result;
10043: } else {
10044: $result=$result>$before?$result:$before;
10045: }
10046: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10047: $operand=$chunk;
10048: } else {
10049: my $new=directcondval($chunk);
10050: if ($operand eq '&') {
10051: $result=$result>$new?$new:$result;
10052: } else {
10053: $result=$result>$new?$result:$new;
10054: }
10055: }
10056: }
1.26 www 10057: }
10058: return $result;
1.421 albertel 10059: }
10060:
10061: # ---------------------------------------------------- Devalidate courseresdata
10062:
10063: sub devalidatecourseresdata {
10064: my ($coursenum,$coursedomain)=@_;
10065: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10066: &devalidate_cache_new('courseres',$hashid);
1.28 www 10067: }
10068:
1.763 www 10069:
1.200 www 10070: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10071: #
10072: # Parameters:
10073: # $coursenum - Number of the course.
10074: # $coursedomain - Domain at which the course was created.
10075: # Returns:
10076: # A hash of the course parameters along (I think) with timestamps
10077: # and version info.
1.877 foxr 10078:
1.624 albertel 10079: sub get_courseresdata {
10080: my ($coursenum,$coursedomain)=@_;
1.200 www 10081: my $coursehom=&homeserver($coursenum,$coursedomain);
10082: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10083: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10084: my %dumpreply;
1.417 albertel 10085: unless (defined($cached)) {
1.624 albertel 10086: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10087: $result=\%dumpreply;
1.251 albertel 10088: my ($tmp) = keys(%dumpreply);
10089: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10090: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10091: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10092: return $tmp;
1.416 albertel 10093: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10094: $result=undef;
1.599 albertel 10095: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10096: }
10097: }
1.624 albertel 10098: return $result;
10099: }
10100:
1.633 albertel 10101: sub devalidateuserresdata {
10102: my ($uname,$udom)=@_;
10103: my $hashid="$udom:$uname";
10104: &devalidate_cache_new('userres',$hashid);
10105: }
10106:
1.624 albertel 10107: sub get_userresdata {
10108: my ($uname,$udom)=@_;
10109: #most student don\'t have any data set, check if there is some data
10110: if (&EXT_cache_status($udom,$uname)) { return undef; }
10111:
10112: my $hashid="$udom:$uname";
10113: my ($result,$cached)=&is_cached_new('userres',$hashid);
10114: if (!defined($cached)) {
10115: my %resourcedata=&dump('resourcedata',$udom,$uname);
10116: $result=\%resourcedata;
10117: &do_cache_new('userres',$hashid,$result,600);
10118: }
10119: my ($tmp)=keys(%$result);
10120: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10121: return $result;
10122: }
10123: #error 2 occurs when the .db doesn't exist
10124: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 10125: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10126: &logthis("<font color=\"blue\">WARNING:".
10127: " Trying to get resource data for ".
10128: $uname." at ".$udom.": ".
10129: $tmp."</font>");
10130: }
1.624 albertel 10131: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10132: #&EXT_cache_set($udom,$uname);
10133: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10134: undef($tmp); # not really an error so don't send it back
1.624 albertel 10135: }
10136: return $tmp;
10137: }
1.879 foxr 10138: #----------------------------------------------- resdata - return resource data
10139: # Purpose:
10140: # Return resource data for either users or for a course.
10141: # Parameters:
10142: # $name - Course/user name.
10143: # $domain - Name of the domain the user/course is registered on.
10144: # $type - Type of thing $name is (must be 'course' or 'user'
10145: # @which - Array of names of resources desired.
10146: # Returns:
10147: # The value of the first reasource in @which that is found in the
10148: # resource hash.
10149: # Exceptional Conditions:
10150: # If the $type passed in is not valid (not the string 'course' or
10151: # 'user', an undefined reference is returned.
10152: # If none of the resources are found, an undef is returned
1.624 albertel 10153: sub resdata {
10154: my ($name,$domain,$type,@which)=@_;
10155: my $result;
10156: if ($type eq 'course') {
10157: $result=&get_courseresdata($name,$domain);
10158: } elsif ($type eq 'user') {
10159: $result=&get_userresdata($name,$domain);
10160: }
10161: if (!ref($result)) { return $result; }
1.251 albertel 10162: foreach my $item (@which) {
1.927 albertel 10163: if (defined($result->{$item->[0]})) {
10164: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10165: }
1.250 albertel 10166: }
1.291 albertel 10167: return undef;
1.200 www 10168: }
10169:
1.1172.2.31 raeburn 10170: sub get_numsuppfiles {
10171: my ($cnum,$cdom,$ignorecache)=@_;
10172: my $hashid=$cnum.':'.$cdom;
10173: my ($suppcount,$cached);
10174: unless ($ignorecache) {
10175: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10176: }
10177: unless (defined($cached)) {
10178: my $chome=&homeserver($cnum,$cdom);
10179: unless ($chome eq 'no_host') {
10180: ($suppcount,my $errors) = (0,0);
10181: my $suppmap = 'supplemental.sequence';
10182: ($suppcount,$errors) =
10183: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10184: }
10185: &do_cache_new('suppcount',$hashid,$suppcount,600);
10186: }
10187: return $suppcount;
10188: }
10189:
1.379 matthew 10190: #
10191: # EXT resource caching routines
10192: #
10193:
10194: sub clear_EXT_cache_status {
1.383 albertel 10195: &delenv('cache.EXT.');
1.379 matthew 10196: }
10197:
10198: sub EXT_cache_status {
10199: my ($target_domain,$target_user) = @_;
1.383 albertel 10200: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10201: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10202: # We know already the user has no data
10203: return 1;
10204: } else {
10205: return 0;
10206: }
10207: }
10208:
10209: sub EXT_cache_set {
10210: my ($target_domain,$target_user) = @_;
1.383 albertel 10211: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10212: #&appenv({$cachename => time});
1.379 matthew 10213: }
10214:
1.28 www 10215: # --------------------------------------------------------- Value of a Variable
1.58 www 10216: sub EXT {
1.715 albertel 10217:
1.1172.2.28 raeburn 10218: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10219: unless ($varname) { return ''; }
1.218 albertel 10220: #get real user name/domain, courseid and symb
10221: my $courseid;
1.359 albertel 10222: my $publicuser;
1.427 www 10223: if ($symbparm) {
10224: $symbparm=&get_symb_from_alias($symbparm);
10225: }
1.218 albertel 10226: if (!($uname && $udom)) {
1.790 albertel 10227: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10228: if (!$symbparm) { $symbparm=$cursymb; }
10229: } else {
1.620 albertel 10230: $courseid=$env{'request.course.id'};
1.218 albertel 10231: }
1.48 www 10232: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10233: my $rest;
1.320 albertel 10234: if (defined($therest[0])) {
1.48 www 10235: $rest=join('.',@therest);
10236: } else {
10237: $rest='';
10238: }
1.320 albertel 10239:
1.57 www 10240: my $qualifierrest=$qualifier;
10241: if ($rest) { $qualifierrest.='.'.$rest; }
10242: my $spacequalifierrest=$space;
10243: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10244: if ($realm eq 'user') {
1.48 www 10245: # --------------------------------------------------------------- user.resource
10246: if ($space eq 'resource') {
1.651 albertel 10247: if ( (defined($Apache::lonhomework::parsing_a_problem)
10248: || defined($Apache::lonhomework::parsing_a_task))
10249: &&
1.744 albertel 10250: ($symbparm eq &symbread()) ) {
10251: # if we are in the middle of processing the resource the
10252: # get the value we are planning on committing
10253: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10254: return $Apache::lonhomework::results{$qualifierrest};
10255: } else {
10256: return $Apache::lonhomework::history{$qualifierrest};
10257: }
1.335 albertel 10258: } else {
1.359 albertel 10259: my %restored;
1.620 albertel 10260: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10261: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10262: } else {
10263: %restored=&restore($symbparm,$courseid,$udom,$uname);
10264: }
1.335 albertel 10265: return $restored{$qualifierrest};
10266: }
1.48 www 10267: # ----------------------------------------------------------------- user.access
10268: } elsif ($space eq 'access') {
1.218 albertel 10269: # FIXME - not supporting calls for a specific user
1.48 www 10270: return &allowed($qualifier,$rest);
10271: # ------------------------------------------ user.preferences, user.environment
10272: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10273: if (($uname eq $env{'user.name'}) &&
10274: ($udom eq $env{'user.domain'})) {
10275: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10276: } else {
1.359 albertel 10277: my %returnhash;
10278: if (!$publicuser) {
10279: %returnhash=&userenvironment($udom,$uname,
10280: $qualifierrest);
10281: }
1.218 albertel 10282: return $returnhash{$qualifierrest};
10283: }
1.48 www 10284: # ----------------------------------------------------------------- user.course
10285: } elsif ($space eq 'course') {
1.218 albertel 10286: # FIXME - not supporting calls for a specific user
1.620 albertel 10287: return $env{join('.',('request.course',$qualifier))};
1.48 www 10288: # ------------------------------------------------------------------- user.role
10289: } elsif ($space eq 'role') {
1.218 albertel 10290: # FIXME - not supporting calls for a specific user
1.620 albertel 10291: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10292: if ($qualifier eq 'value') {
10293: return $role;
10294: } elsif ($qualifier eq 'extent') {
10295: return $where;
10296: }
10297: # ----------------------------------------------------------------- user.domain
10298: } elsif ($space eq 'domain') {
1.218 albertel 10299: return $udom;
1.48 www 10300: # ------------------------------------------------------------------- user.name
10301: } elsif ($space eq 'name') {
1.218 albertel 10302: return $uname;
1.48 www 10303: # ---------------------------------------------------- Any other user namespace
1.29 www 10304: } else {
1.359 albertel 10305: my %reply;
10306: if (!$publicuser) {
10307: %reply=&get($space,[$qualifierrest],$udom,$uname);
10308: }
10309: return $reply{$qualifierrest};
1.48 www 10310: }
1.236 www 10311: } elsif ($realm eq 'query') {
10312: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10313: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10314: [$spacequalifierrest]);
1.620 albertel 10315: return $env{'form.'.$spacequalifierrest};
1.236 www 10316: } elsif ($realm eq 'request') {
1.48 www 10317: # ------------------------------------------------------------- request.browser
10318: if ($space eq 'browser') {
1.1145 bisitz 10319: return $env{'browser.'.$qualifier};
1.57 www 10320: # ------------------------------------------------------------ request.filename
10321: } else {
1.620 albertel 10322: return $env{'request.'.$spacequalifierrest};
1.29 www 10323: }
1.28 www 10324: } elsif ($realm eq 'course') {
1.48 www 10325: # ---------------------------------------------------------- course.description
1.620 albertel 10326: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10327: } elsif ($realm eq 'resource') {
1.165 www 10328:
1.620 albertel 10329: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10330: if (!$symbparm) { $symbparm=&symbread(); }
10331: }
1.693 albertel 10332:
1.1172.2.30 raeburn 10333: if ($qualifier eq '') {
10334: if ($space eq 'title') {
10335: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10336: return &gettitle($symbparm);
10337: }
1.693 albertel 10338:
1.1172.2.30 raeburn 10339: if ($space eq 'map') {
10340: my ($map) = &decode_symb($symbparm);
10341: return &symbread($map);
10342: }
10343: if ($space eq 'maptitle') {
10344: my ($map) = &decode_symb($symbparm);
10345: return &gettitle($map);
10346: }
10347: if ($space eq 'filename') {
10348: if ($symbparm) {
10349: return &clutter((&decode_symb($symbparm))[2]);
10350: }
10351: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10352: }
1.1172.2.30 raeburn 10353:
10354: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10355: if ($space eq 'visibleparts') {
10356: my $navmap = Apache::lonnavmaps::navmap->new();
10357: my $item;
10358: if (ref($navmap)) {
10359: my $res = $navmap->getBySymb($symbparm);
10360: my $parts = $res->parts();
10361: if (ref($parts) eq 'ARRAY') {
10362: $item = join(',',@{$parts});
10363: }
10364: undef($navmap);
10365: }
10366: return $item;
10367: }
10368: }
10369: }
1.693 albertel 10370:
10371: my ($section, $group, @groups);
1.593 albertel 10372: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 10373: if (($courseid eq '') && ($cid)) {
10374: $courseid = $cid;
10375: }
10376: if (($symbparm && $courseid) &&
10377: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10378:
1.218 albertel 10379: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10380:
1.60 www 10381: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10382: my $symbp=$symbparm;
1.735 albertel 10383: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10384:
10385: my $symbparm=$symbp.'.'.$spacequalifierrest;
10386: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10387:
1.620 albertel 10388: if (($env{'user.name'} eq $uname) &&
10389: ($env{'user.domain'} eq $udom)) {
10390: $section=$env{'request.course.sec'};
1.733 raeburn 10391: @groups = split(/:/,$env{'request.course.groups'});
10392: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10393: } else {
1.539 albertel 10394: if (! defined($usection)) {
1.551 albertel 10395: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10396: } else {
10397: $section = $usection;
10398: }
1.733 raeburn 10399: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10400: }
10401:
10402: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10403: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10404: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10405:
1.593 albertel 10406: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10407: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10408: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10409:
1.60 www 10410: # ----------------------------------------------------------- first, check user
1.624 albertel 10411:
10412: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10413: ([$courselevelr,'resource'],
10414: [$courselevelm,'map' ],
10415: [$courselevel, 'course' ]));
1.931 albertel 10416: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10417:
1.594 albertel 10418: # ------------------------------------------------ second, check some of course
1.684 raeburn 10419: my $coursereply;
1.691 raeburn 10420: if (@groups > 0) {
10421: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10422: $mapparm,$spacequalifierrest);
1.927 albertel 10423: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10424: }
1.96 www 10425:
1.684 raeburn 10426: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10427: $env{'course.'.$courseid.'.domain'},
10428: 'course',
10429: ([$seclevelr, 'resource'],
10430: [$seclevelm, 'map' ],
10431: [$seclevel, 'course' ],
10432: [$courselevelr,'resource']));
10433: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10434:
1.60 www 10435: # ------------------------------------------------------ third, check map parms
1.218 albertel 10436: my %parmhash=();
10437: my $thisparm='';
10438: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10439: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10440: &GDBM_READER(),0640)) {
1.218 albertel 10441: $thisparm=$parmhash{$symbparm};
10442: untie(%parmhash);
10443: }
1.927 albertel 10444: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10445: }
1.594 albertel 10446: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10447:
1.218 albertel 10448: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10449: my $filename;
10450: if (!$symbparm) { $symbparm=&symbread(); }
10451: if ($symbparm) {
1.409 www 10452: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10453: } else {
1.620 albertel 10454: $filename=$env{'request.filename'};
1.282 albertel 10455: }
10456: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10457: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10458: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10459: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10460:
1.927 albertel 10461: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10462: if ($symbparm && defined($courseid) &&
1.620 albertel 10463: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10464: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10465: $env{'course.'.$courseid.'.domain'},
10466: 'course',
1.927 albertel 10467: ([$courselevelm,'map' ],
10468: [$courselevel, 'course']));
10469: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10470: }
1.145 www 10471: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10472: unless ($space eq '0') {
1.336 albertel 10473: my @parts=split(/_/,$space);
10474: my $id=pop(@parts);
10475: my $part=join('_',@parts);
10476: if ($part eq '') { $part='0'; }
1.927 albertel 10477: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10478: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10479: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10480: }
1.395 albertel 10481: if ($recurse) { return undef; }
10482: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10483: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10484: # ---------------------------------------------------- Any other user namespace
10485: } elsif ($realm eq 'environment') {
10486: # ----------------------------------------------------------------- environment
1.620 albertel 10487: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10488: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10489: } else {
1.770 albertel 10490: if ($uname eq 'anonymous' && $udom eq '') {
10491: return '';
10492: }
1.219 albertel 10493: my %returnhash=&userenvironment($udom,$uname,
10494: $spacequalifierrest);
10495: return $returnhash{$spacequalifierrest};
10496: }
1.28 www 10497: } elsif ($realm eq 'system') {
1.48 www 10498: # ----------------------------------------------------------------- system.time
10499: if ($space eq 'time') {
10500: return time;
10501: }
1.696 albertel 10502: } elsif ($realm eq 'server') {
10503: # ----------------------------------------------------------------- system.time
10504: if ($space eq 'name') {
10505: return $ENV{'SERVER_NAME'};
10506: }
1.28 www 10507: }
1.48 www 10508: return '';
1.61 www 10509: }
10510:
1.927 albertel 10511: sub get_reply {
10512: my ($reply_value) = @_;
1.940 raeburn 10513: if (ref($reply_value) eq 'ARRAY') {
10514: if (wantarray) {
10515: return @$reply_value;
10516: }
10517: return $reply_value->[0];
10518: } else {
10519: return $reply_value;
1.927 albertel 10520: }
10521: }
10522:
1.691 raeburn 10523: sub check_group_parms {
10524: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10525: my @groupitems = ();
10526: my $resultitem;
1.927 albertel 10527: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10528: foreach my $group (@{$groups}) {
10529: foreach my $level (@levels) {
1.927 albertel 10530: my $item = $courseid.'.['.$group.'].'.$level->[0];
10531: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10532: }
10533: }
10534: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10535: $env{'course.'.$courseid.'.domain'},
10536: 'course',@groupitems);
10537: return $coursereply;
10538: }
10539:
10540: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10541: my ($courseid,@groups) = @_;
10542: @groups = sort(@groups);
1.691 raeburn 10543: return @groups;
10544: }
10545:
1.395 albertel 10546: sub packages_tab_default {
10547: my ($uri,$varname)=@_;
10548: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10549:
10550: my (@extension,@specifics,$do_default);
10551: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10552: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10553: if ($pack_type eq 'default') {
10554: $do_default=1;
10555: } elsif ($pack_type eq 'extension') {
10556: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10557: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10558: # only look at packages defaults for packages that this id is
1.738 albertel 10559: push(@specifics,[$package,$pack_type,$pack_part]);
10560: }
10561: }
10562: # first look for a package that matches the requested part id
10563: foreach my $package (@specifics) {
10564: my (undef,$pack_type,$pack_part)=@{$package};
10565: next if ($pack_part ne $part);
10566: if (defined($packagetab{"$pack_type&$name&default"})) {
10567: return $packagetab{"$pack_type&$name&default"};
10568: }
10569: }
10570: # look for any possible matching non extension_ package
10571: foreach my $package (@specifics) {
10572: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10573: if (defined($packagetab{"$pack_type&$name&default"})) {
10574: return $packagetab{"$pack_type&$name&default"};
10575: }
1.585 albertel 10576: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10577: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10578: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10579: }
10580: }
1.738 albertel 10581: # look for any posible extension_ match
10582: foreach my $package (@extension) {
10583: my ($package,$pack_type)=@{$package};
10584: if (defined($packagetab{"$pack_type&$name&default"})) {
10585: return $packagetab{"$pack_type&$name&default"};
10586: }
10587: if (defined($packagetab{$package."&$name&default"})) {
10588: return $packagetab{$package."&$name&default"};
10589: }
10590: }
10591: # look for a global default setting
10592: if ($do_default && defined($packagetab{"default&$name&default"})) {
10593: return $packagetab{"default&$name&default"};
10594: }
1.395 albertel 10595: return undef;
10596: }
10597:
1.334 albertel 10598: sub add_prefix_and_part {
10599: my ($prefix,$part)=@_;
10600: my $keyroot;
10601: if (defined($prefix) && $prefix !~ /^__/) {
10602: # prefix that has a part already
10603: $keyroot=$prefix;
10604: } elsif (defined($prefix)) {
10605: # prefix that is missing a part
10606: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10607: } else {
10608: # no prefix at all
10609: if (defined($part)) { $keyroot='_'.$part; }
10610: }
10611: return $keyroot;
10612: }
10613:
1.71 www 10614: # ---------------------------------------------------------------- Get metadata
10615:
1.599 albertel 10616: my %metaentry;
1.1070 www 10617: my %importedpartids;
1.71 www 10618: sub metadata {
1.176 www 10619: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10620: $uri=&declutter($uri);
1.288 albertel 10621: # if it is a non metadata possible uri return quickly
1.529 albertel 10622: if (($uri eq '') ||
10623: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 10624: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10625: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10626: return undef;
10627: }
1.1172.2.49 raeburn 10628: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10629: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10630: return undef;
1.288 albertel 10631: }
1.73 www 10632: my $filename=$uri;
10633: $uri=~s/\.meta$//;
1.172 www 10634: #
10635: # Is the metadata already cached?
1.177 www 10636: # Look at timestamp of caching
1.172 www 10637: # Everything is cached by the main uri, libraries are never directly cached
10638: #
1.428 albertel 10639: if (!defined($liburi)) {
1.599 albertel 10640: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10641: if (defined($cached)) { return $result->{':'.$what}; }
10642: }
10643: {
1.1069 www 10644: # Imported parts would go here
1.1070 www 10645: my %importedids=();
10646: my @origfileimportpartids=();
1.1069 www 10647: my $importedparts=0;
1.172 www 10648: #
10649: # Is this a recursive call for a library?
10650: #
1.599 albertel 10651: # if (! exists($metacache{$uri})) {
10652: # $metacache{$uri}={};
10653: # }
1.924 albertel 10654: my $cachetime = 60*60;
1.171 www 10655: if ($liburi) {
10656: $liburi=&declutter($liburi);
10657: $filename=$liburi;
1.401 bowersj2 10658: } else {
1.599 albertel 10659: &devalidate_cache_new('meta',$uri);
10660: undef(%metaentry);
1.401 bowersj2 10661: }
1.140 www 10662: my %metathesekeys=();
1.73 www 10663: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10664: my $metastring;
1.1140 www 10665: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10666: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10667: $metastring =
1.929 albertel 10668: &Apache::lonnet::ssi_body($which,
1.924 albertel 10669: ('grade_target' => 'meta'));
10670: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10671: } elsif (($uri !~ m -^(editupload)/-) &&
10672: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10673: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10674: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10675: $metastring=&getfile($file);
1.489 albertel 10676: }
1.208 albertel 10677: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10678: my $token;
1.140 www 10679: undef %metathesekeys;
1.71 www 10680: while ($token=$parser->get_token) {
1.339 albertel 10681: if ($token->[0] eq 'S') {
10682: if (defined($token->[2]->{'package'})) {
1.172 www 10683: #
10684: # This is a package - get package info
10685: #
1.339 albertel 10686: my $package=$token->[2]->{'package'};
10687: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10688: if (defined($token->[2]->{'id'})) {
10689: $keyroot.='_'.$token->[2]->{'id'};
10690: }
1.599 albertel 10691: if ($metaentry{':packages'}) {
10692: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10693: } else {
1.599 albertel 10694: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10695: }
1.736 albertel 10696: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10697: my $part=$keyroot;
10698: $part=~s/^\_//;
1.736 albertel 10699: if ($pack_entry=~/^\Q$package\E\&/ ||
10700: $pack_entry=~/^\Q$package\E_0\&/) {
10701: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10702: # ignore package.tab specified default values
10703: # here &package_tab_default() will fetch those
10704: if ($subp eq 'default') { next; }
1.736 albertel 10705: my $value=$packagetab{$pack_entry};
1.432 albertel 10706: my $unikey;
10707: if ($pack =~ /_0$/) {
10708: $unikey='parameter_0_'.$name;
10709: $part=0;
10710: } else {
10711: $unikey='parameter'.$keyroot.'_'.$name;
10712: }
1.339 albertel 10713: if ($subp eq 'display') {
10714: $value.=' [Part: '.$part.']';
10715: }
1.599 albertel 10716: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10717: $metathesekeys{$unikey}=1;
1.599 albertel 10718: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10719: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10720: }
1.599 albertel 10721: if (defined($metaentry{':'.$unikey.'.default'})) {
10722: $metaentry{':'.$unikey}=
10723: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10724: }
1.339 albertel 10725: }
10726: }
10727: } else {
1.172 www 10728: #
10729: # This is not a package - some other kind of start tag
1.339 albertel 10730: #
10731: my $entry=$token->[1];
1.1068 www 10732: my $unikey='';
1.175 www 10733:
1.339 albertel 10734: if ($entry eq 'import') {
1.175 www 10735: #
10736: # Importing a library here
1.339 albertel 10737: #
1.1067 www 10738: my $location=$parser->get_text('/import');
10739: my $dir=$filename;
10740: $dir=~s|[^/]*$||;
10741: $location=&filelocation($dir,$location);
1.1069 www 10742:
1.1068 www 10743: my $importmode=$token->[2]->{'importmode'};
10744: if ($importmode eq 'problem') {
1.1069 www 10745: # Import as problem/response
1.1068 www 10746: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10747: } elsif ($importmode eq 'part') {
10748: # Import as part(s)
1.1069 www 10749: $importedparts=1;
10750: # We need to get the original file and the imported file to get the part order correct
10751: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10752: # Load and inspect original file
1.1070 www 10753: if ($#origfileimportpartids<0) {
10754: undef(%importedpartids);
10755: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10756: my $origfile=&getfile($origfilelocation);
10757: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10758: }
10759:
1.1069 www 10760: # Load and inspect imported file
10761: my $impfile=&getfile($location);
10762: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10763: if ($#impfilepartids>=0) {
10764: # This problem had parts
1.1070 www 10765: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10766: } else {
10767: # Importing by turning a single problem into a problem part
10768: # It gets the import-tags ID as part-ID
10769: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10770: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10771: }
1.1068 www 10772: } else {
10773: # Normal import
10774: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10775: if (defined($token->[2]->{'id'})) {
10776: $unikey.='_'.$token->[2]->{'id'};
10777: }
1.1067 www 10778: }
10779:
1.339 albertel 10780: if ($depthcount<20) {
1.736 albertel 10781: my $metadata =
10782: &metadata($uri,'keys', $location,$unikey,
10783: $depthcount+1);
10784: foreach my $meta (split(',',$metadata)) {
10785: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10786: $metathesekeys{$meta}=1;
1.339 albertel 10787: }
1.1068 www 10788:
10789: }
1.1067 www 10790: } else {
10791: #
10792: # Not importing, some other kind of non-package, non-library start tag
10793: #
10794: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10795: if (defined($token->[2]->{'id'})) {
10796: $unikey.='_'.$token->[2]->{'id'};
10797: }
1.339 albertel 10798: if (defined($token->[2]->{'name'})) {
10799: $unikey.='_'.$token->[2]->{'name'};
10800: }
10801: $metathesekeys{$unikey}=1;
1.736 albertel 10802: foreach my $param (@{$token->[3]}) {
10803: $metaentry{':'.$unikey.'.'.$param} =
10804: $token->[2]->{$param};
1.339 albertel 10805: }
10806: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10807: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10808: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10809: # only ws inside the tag, and not in default, so use default
10810: # as value
1.599 albertel 10811: $metaentry{':'.$unikey}=$default;
1.908 albertel 10812: } elsif ( $internaltext =~ /\S/ ) {
10813: # something interesting inside the tag
10814: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10815: } else {
1.908 albertel 10816: # no interesting values, don't set a default
1.339 albertel 10817: }
1.172 www 10818: # end of not-a-package not-a-library import
1.339 albertel 10819: }
1.172 www 10820: # end of not-a-package start tag
1.339 albertel 10821: }
1.172 www 10822: # the next is the end of "start tag"
1.339 albertel 10823: }
10824: }
1.483 albertel 10825: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10826: $extension = lc($extension);
10827: if ($extension eq 'htm') { $extension='html'; }
10828:
1.737 albertel 10829: foreach my $key (keys(%packagetab)) {
1.483 albertel 10830: #no specific packages #how's our extension
10831: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10832: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10833: \%metathesekeys);
10834: }
1.883 albertel 10835:
10836: if (!exists($metaentry{':packages'})
10837: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10838: foreach my $key (keys(%packagetab)) {
1.483 albertel 10839: #no specific packages well let's get default then
10840: if ($key!~/^default&/) { next; }
1.488 albertel 10841: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10842: \%metathesekeys);
10843: }
10844: }
1.338 www 10845: # are there custom rights to evaluate
1.599 albertel 10846: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10847:
1.338 www 10848: #
10849: # Importing a rights file here
1.339 albertel 10850: #
10851: unless ($depthcount) {
1.599 albertel 10852: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10853: my $dir=$filename;
10854: $dir=~s|[^/]*$||;
10855: $location=&filelocation($dir,$location);
1.736 albertel 10856: my $rights_metadata =
10857: &metadata($uri,'keys',$location,'_rights',
10858: $depthcount+1);
10859: foreach my $rights (split(',',$rights_metadata)) {
10860: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10861: $metathesekeys{$rights}=1;
1.339 albertel 10862: }
10863: }
10864: }
1.737 albertel 10865: # uniqifiy package listing
10866: my %seen;
10867: my @uniq_packages =
10868: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10869: $metaentry{':packages'} = join(',',@uniq_packages);
10870:
1.1070 www 10871: if ($importedparts) {
10872: # We had imported parts and need to rebuild partorder
10873: $metaentry{':partorder'}='';
10874: $metathesekeys{'partorder'}=1;
10875: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10876: if ($origfileimportpartids[$index] eq 'part') {
10877: # original part, part of the problem
10878: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10879: } else {
10880: # we have imported parts at this position
10881: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10882: }
10883: }
10884: $metaentry{':partorder'}=~s/^\,//;
10885: }
10886:
1.737 albertel 10887: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10888: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 10889: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 10890: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10891: # this is the end of "was not already recently cached
1.71 www 10892: }
1.599 albertel 10893: return $metaentry{':'.$what};
1.261 albertel 10894: }
10895:
1.488 albertel 10896: sub metadata_create_package_def {
1.483 albertel 10897: my ($uri,$key,$package,$metathesekeys)=@_;
10898: my ($pack,$name,$subp)=split(/\&/,$key);
10899: if ($subp eq 'default') { next; }
10900:
1.599 albertel 10901: if (defined($metaentry{':packages'})) {
10902: $metaentry{':packages'}.=','.$package;
1.483 albertel 10903: } else {
1.599 albertel 10904: $metaentry{':packages'}=$package;
1.483 albertel 10905: }
10906: my $value=$packagetab{$key};
10907: my $unikey;
10908: $unikey='parameter_0_'.$name;
1.599 albertel 10909: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10910: $$metathesekeys{$unikey}=1;
1.599 albertel 10911: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10912: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10913: }
1.599 albertel 10914: if (defined($metaentry{':'.$unikey.'.default'})) {
10915: $metaentry{':'.$unikey}=
10916: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10917: }
10918: }
10919:
1.261 albertel 10920: sub metadata_generate_part0 {
10921: my ($metadata,$metacache,$uri) = @_;
10922: my %allnames;
1.737 albertel 10923: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10924: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10925: my $part=$$metacache{':'.$metakey.'.part'};
10926: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10927: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10928: $allnames{$name}=$part;
10929: }
10930: }
10931: }
10932: foreach my $name (keys(%allnames)) {
10933: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10934: my $key=":parameter_0_$name";
1.261 albertel 10935: $$metacache{"$key.part"}='0';
10936: $$metacache{"$key.name"}=$name;
1.428 albertel 10937: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10938: $allnames{$name}.'_'.$name.
10939: '.type'};
1.428 albertel 10940: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10941: '.display'};
1.644 www 10942: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10943: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10944: $$metacache{"$key.display"}=$olddis;
10945: }
1.71 www 10946: }
10947:
1.764 albertel 10948: # ------------------------------------------------------ Devalidate title cache
10949:
10950: sub devalidate_title_cache {
10951: my ($url)=@_;
10952: if (!$env{'request.course.id'}) { return; }
10953: my $symb=&symbread($url);
10954: if (!$symb) { return; }
10955: my $key=$env{'request.course.id'}."\0".$symb;
10956: &devalidate_cache_new('title',$key);
10957: }
10958:
1.1014 droeschl 10959: # ------------------------------------------------- Get the title of a course
10960:
10961: sub current_course_title {
10962: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10963: }
1.301 www 10964: # ------------------------------------------------- Get the title of a resource
10965:
10966: sub gettitle {
10967: my $urlsymb=shift;
10968: my $symb=&symbread($urlsymb);
1.534 albertel 10969: if ($symb) {
1.620 albertel 10970: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10971: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10972: if (defined($cached)) {
10973: return $result;
10974: }
1.534 albertel 10975: my ($map,$resid,$url)=&decode_symb($symb);
10976: my $title='';
1.907 albertel 10977: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10978: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10979: } else {
10980: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10981: &GDBM_READER(),0640)) {
10982: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10983: $title=$bighash{'title_'.$mapid.'.'.$resid};
10984: untie(%bighash);
10985: }
1.534 albertel 10986: }
10987: $title=~s/\&colon\;/\:/gs;
10988: if ($title) {
1.1159 www 10989: # Remember both $symb and $title for dynamic metadata
10990: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10991: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10992: # Cache this title and then return it
1.599 albertel 10993: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10994: }
10995: $urlsymb=$url;
10996: }
10997: my $title=&metadata($urlsymb,'title');
10998: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10999: return $title;
1.301 www 11000: }
1.613 albertel 11001:
1.614 albertel 11002: sub get_slot {
11003: my ($which,$cnum,$cdom)=@_;
11004: if (!$cnum || !$cdom) {
1.790 albertel 11005: (undef,my $courseid)=&whichuser();
1.620 albertel 11006: $cdom=$env{'course.'.$courseid.'.domain'};
11007: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11008: }
1.703 albertel 11009: my $key=join("\0",'slots',$cdom,$cnum,$which);
11010: my %slotinfo;
11011: if (exists($remembered{$key})) {
11012: $slotinfo{$which} = $remembered{$key};
11013: } else {
11014: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11015: &Apache::lonhomework::showhash(%slotinfo);
11016: my ($tmp)=keys(%slotinfo);
11017: if ($tmp=~/^error:/) { return (); }
11018: $remembered{$key} = $slotinfo{$which};
11019: }
1.616 albertel 11020: if (ref($slotinfo{$which}) eq 'HASH') {
11021: return %{$slotinfo{$which}};
11022: }
11023: return $slotinfo{$which};
1.614 albertel 11024: }
1.1150 raeburn 11025:
11026: sub get_reservable_slots {
11027: my ($cnum,$cdom,$uname,$udom) = @_;
11028: my $now = time;
11029: my $reservable_info;
11030: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11031: if (exists($remembered{$key})) {
11032: $reservable_info = $remembered{$key};
11033: } else {
11034: my %resv;
11035: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11036: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11037: $reservable_info = \%resv;
11038: $remembered{$key} = $reservable_info;
11039: }
11040: return $reservable_info;
11041: }
11042:
11043: sub get_course_slots {
11044: my ($cnum,$cdom) = @_;
11045: my $hashid=$cnum.':'.$cdom;
11046: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11047: if (defined($cached)) {
11048: if (ref($result) eq 'HASH') {
11049: return %{$result};
11050: }
11051: } else {
11052: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11053: my ($tmp) = keys(%slots);
11054: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 11055: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11056: return %slots;
11057: }
11058: }
11059: return;
11060: }
11061:
11062: sub devalidate_slots_cache {
11063: my ($cnum,$cdom)=@_;
11064: my $hashid=$cnum.':'.$cdom;
11065: &devalidate_cache_new('allslots',$hashid);
11066: }
11067:
1.1172.2.8 raeburn 11068: sub get_coursechange {
11069: my ($cdom,$cnum) = @_;
11070: if ($cdom eq '' || $cnum eq '') {
11071: return unless ($env{'request.course.id'});
11072: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11073: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11074: }
11075: my $hashid=$cdom.'_'.$cnum;
11076: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11077: if ((defined($cached)) && ($change ne '')) {
11078: return $change;
11079: } else {
11080: my %crshash;
11081: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11082: if ($crshash{'internal.contentchange'} eq '') {
11083: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11084: if ($change eq '') {
11085: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11086: $change = $crshash{'internal.created'};
11087: }
11088: } else {
11089: $change = $crshash{'internal.contentchange'};
11090: }
11091: my $cachetime = 600;
11092: &do_cache_new('crschange',$hashid,$change,$cachetime);
11093: }
11094: return $change;
11095: }
11096:
11097: sub devalidate_coursechange_cache {
11098: my ($cnum,$cdom)=@_;
11099: my $hashid=$cnum.':'.$cdom;
11100: &devalidate_cache_new('crschange',$hashid);
11101: }
11102:
1.31 www 11103: # ------------------------------------------------- Update symbolic store links
11104:
11105: sub symblist {
11106: my ($mapname,%newhash)=@_;
1.438 www 11107: $mapname=&deversion(&declutter($mapname));
1.31 www 11108: my %hash;
1.620 albertel 11109: if (($env{'request.course.fn'}) && (%newhash)) {
11110: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11111: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11112: foreach my $url (keys(%newhash)) {
1.711 albertel 11113: next if ($url eq 'last_known'
11114: && $env{'form.no_update_last_known'});
11115: $hash{declutter($url)}=&encode_symb($mapname,
11116: $newhash{$url}->[1],
11117: $newhash{$url}->[0]);
1.191 harris41 11118: }
1.31 www 11119: if (untie(%hash)) {
11120: return 'ok';
11121: }
11122: }
11123: }
11124: return 'error';
1.212 www 11125: }
11126:
11127: # --------------------------------------------------------------- Verify a symb
11128:
11129: sub symbverify {
1.1172.2.11 raeburn 11130: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11131: my $thisfn=$thisurl;
1.439 www 11132: $thisfn=&declutter($thisfn);
1.215 www 11133: # direct jump to resource in page or to a sequence - will construct own symbs
11134: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11135: # check URL part
1.409 www 11136: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11137:
1.431 www 11138: unless ($url eq $thisfn) { return 0; }
1.213 www 11139:
1.216 www 11140: $symb=&symbclean($symb);
1.510 www 11141: $thisurl=&deversion($thisurl);
1.439 www 11142: $thisfn=&deversion($thisfn);
1.213 www 11143:
11144: my %bighash;
11145: my $okay=0;
1.431 www 11146:
1.620 albertel 11147: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11148: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 11149: my $noclutter;
1.1032 raeburn 11150: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11151: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 11152: if ($map =~ m{^uploaded/.+\.page$}) {
11153: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11154: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11155: $noclutter = 1;
11156: }
11157: }
11158: my $ids;
11159: if ($noclutter) {
11160: $ids=$bighash{'ids_'.$thisurl};
11161: } else {
11162: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11163: }
1.1102 raeburn 11164: unless ($ids) {
1.1172.2.13 raeburn 11165: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 11166: $ids=$bighash{$idkey};
1.216 www 11167: }
11168: if ($ids) {
11169: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 11170: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
11171: $symb =~ s/\?.+$//;
11172: }
1.800 albertel 11173: foreach my $id (split(/\,/,$ids)) {
11174: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11175: if (
11176: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 11177: eq $symb) {
1.1172.2.11 raeburn 11178: if (ref($encstate)) {
11179: $$encstate = $bighash{'encrypted_'.$id};
11180: }
1.1172.2.13 raeburn 11181: if (($env{'request.role.adv'}) ||
11182: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 11183: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 11184: $okay=1;
11185: last;
11186: }
11187: }
11188: }
1.216 www 11189: }
1.213 www 11190: untie(%bighash);
11191: }
11192: return $okay;
1.31 www 11193: }
11194:
1.210 www 11195: # --------------------------------------------------------------- Clean-up symb
11196:
11197: sub symbclean {
11198: my $symb=shift;
1.568 albertel 11199: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11200: # remove version from map
11201: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11202:
1.210 www 11203: # remove version from URL
11204: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11205:
1.507 www 11206: # remove wrapper
11207:
1.510 www 11208: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11209: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11210: return $symb;
1.409 www 11211: }
11212:
11213: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11214:
11215: sub encode_symb {
11216: my ($map,$resid,$url)=@_;
11217: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11218: }
1.409 www 11219:
11220: sub decode_symb {
1.568 albertel 11221: my $symb=shift;
11222: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11223: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11224: return (&fixversion($map),$resid,&fixversion($url));
11225: }
11226:
11227: sub fixversion {
11228: my $fn=shift;
1.609 banghart 11229: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11230: my %bighash;
11231: my $uri=&clutter($fn);
1.620 albertel 11232: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11233: # is this cached?
1.599 albertel 11234: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11235: if (defined($cached)) { return $result; }
11236: # unfortunately not cached, or expired
1.620 albertel 11237: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11238: &GDBM_READER(),0640)) {
11239: if ($bighash{'version_'.$uri}) {
11240: my $version=$bighash{'version_'.$uri};
1.444 www 11241: unless (($version eq 'mostrecent') ||
11242: ($version==&getversion($uri))) {
1.440 www 11243: $uri=~s/\.(\w+)$/\.$version\.$1/;
11244: }
11245: }
11246: untie %bighash;
1.413 www 11247: }
1.599 albertel 11248: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11249: }
11250:
11251: sub deversion {
11252: my $url=shift;
11253: $url=~s/\.\d+\.(\w+)$/\.$1/;
11254: return $url;
1.210 www 11255: }
11256:
1.31 www 11257: # ------------------------------------------------------ Return symb list entry
11258:
11259: sub symbread {
1.1172.2.66 raeburn 11260: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54 raeburn 11261: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66 raeburn 11262: if (defined($env{$cache_str})) {
11263: if ($ignorecachednull) {
11264: return $env{$cache_str} unless ($env{$cache_str} eq '');
11265: } else {
11266: return $env{$cache_str};
11267: }
11268: }
1.242 www 11269: # no filename provided? try from environment
1.1172.2.54 raeburn 11270: unless ($thisfn) {
1.620 albertel 11271: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 11272: return $env{$cache_str}=&symbclean($env{'request.symb'});
11273: }
11274: $thisfn=$env{'request.filename'};
1.44 www 11275: }
1.569 albertel 11276: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11277: # is that filename actually a symb? Verify, clean, and return
11278: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11279: if (&symbverify($thisfn,$1)) {
1.620 albertel 11280: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11281: }
1.242 www 11282: }
1.44 www 11283: $thisfn=declutter($thisfn);
1.31 www 11284: my %hash;
1.37 www 11285: my %bighash;
11286: my $syval='';
1.620 albertel 11287: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11288: my $targetfn = $thisfn;
1.609 banghart 11289: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11290: $targetfn = 'adm/wrapper/'.$thisfn;
11291: }
1.687 albertel 11292: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11293: $targetfn=$1;
11294: }
1.620 albertel 11295: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11296: &GDBM_READER(),0640)) {
1.481 raeburn 11297: $syval=$hash{$targetfn};
1.37 www 11298: untie(%hash);
11299: }
11300: # ---------------------------------------------------------- There was an entry
11301: if ($syval) {
1.601 albertel 11302: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11303: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11304: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11305: #return $env{$cache_str}='';
1.601 albertel 11306: #}
11307: #$syval.=$1;
11308: #}
1.37 www 11309: } else {
11310: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11311: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11312: &GDBM_READER(),0640)) {
1.37 www 11313: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11314: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11315: unless ($ids) {
11316: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11317: }
11318: unless ($ids) {
11319: # alias?
11320: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11321: }
1.37 www 11322: if ($ids) {
11323: # ------------------------------------------------------------------- Has ID(s)
11324: my @possibilities=split(/\,/,$ids);
1.39 www 11325: if ($#possibilities==0) {
11326: # ----------------------------------------------- There is only one possibility
1.37 www 11327: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11328: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11329: $resid,$thisfn);
1.1172.2.66 raeburn 11330: if (ref($possibles) eq 'HASH') {
11331: $possibles->{$syval} = 1;
11332: }
11333: if ($checkforblock) {
11334: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11335: if (@blockers) {
11336: $syval = '';
11337: return;
11338: }
11339: }
11340: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11341: # ------------------------------------------ There is more than one possibility
11342: my $realpossible=0;
1.800 albertel 11343: foreach my $id (@possibilities) {
11344: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 11345: my $canaccess;
11346: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11347: $canaccess = 1;
11348: } else {
11349: $canaccess = &allowed('bre',$file);
11350: }
11351: if ($canaccess) {
11352: my ($mapid,$resid)=split(/\./,$id);
11353: if ($bighash{'map_type_'.$mapid} ne 'page') {
11354: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11355: $resid,$thisfn);
11356: if (ref($possibles) eq 'HASH') {
11357: $possibles->{$syval} = 1;
11358: }
11359: if ($checkforblock) {
11360: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11361: unless (@blockers > 0) {
11362: $syval = $poss_syval;
11363: $realpossible++;
11364: }
11365: } else {
11366: $syval = $poss_syval;
11367: $realpossible++;
11368: }
11369: }
1.39 www 11370: }
1.191 harris41 11371: }
1.39 www 11372: if ($realpossible!=1) { $syval=''; }
1.249 www 11373: } else {
11374: $syval='';
1.37 www 11375: }
11376: }
1.1172.2.66 raeburn 11377: untie(%bighash);
1.481 raeburn 11378: }
1.31 www 11379: }
1.62 www 11380: if ($syval) {
1.620 albertel 11381: return $env{$cache_str}=$syval;
1.62 www 11382: }
1.31 www 11383: }
1.949 raeburn 11384: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11385: return $env{$cache_str}='';
1.31 www 11386: }
11387:
11388: # ---------------------------------------------------------- Return random seed
11389:
1.32 www 11390: sub numval {
11391: my $txt=shift;
11392: $txt=~tr/A-J/0-9/;
11393: $txt=~tr/a-j/0-9/;
11394: $txt=~tr/K-T/0-9/;
11395: $txt=~tr/k-t/0-9/;
11396: $txt=~tr/U-Z/0-5/;
11397: $txt=~tr/u-z/0-5/;
11398: $txt=~s/\D//g;
1.564 albertel 11399: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11400: return int($txt);
1.368 albertel 11401: }
11402:
1.484 albertel 11403: sub numval2 {
11404: my $txt=shift;
11405: $txt=~tr/A-J/0-9/;
11406: $txt=~tr/a-j/0-9/;
11407: $txt=~tr/K-T/0-9/;
11408: $txt=~tr/k-t/0-9/;
11409: $txt=~tr/U-Z/0-5/;
11410: $txt=~tr/u-z/0-5/;
11411: $txt=~s/\D//g;
11412: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11413: my $total;
11414: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11415: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11416: return int($total);
11417: }
11418:
1.575 albertel 11419: sub numval3 {
11420: use integer;
11421: my $txt=shift;
11422: $txt=~tr/A-J/0-9/;
11423: $txt=~tr/a-j/0-9/;
11424: $txt=~tr/K-T/0-9/;
11425: $txt=~tr/k-t/0-9/;
11426: $txt=~tr/U-Z/0-5/;
11427: $txt=~tr/u-z/0-5/;
11428: $txt=~s/\D//g;
11429: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11430: my $total;
11431: foreach my $val (@txts) { $total+=$val; }
11432: if ($_64bit) { $total=(($total<<32)>>32); }
11433: return $total;
11434: }
11435:
1.675 albertel 11436: sub digest {
11437: my ($data)=@_;
11438: my $digest=&Digest::MD5::md5($data);
11439: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11440: my ($e,$f);
11441: {
11442: use integer;
11443: $e=($a+$b);
11444: $f=($c+$d);
11445: if ($_64bit) {
11446: $e=(($e<<32)>>32);
11447: $f=(($f<<32)>>32);
11448: }
11449: }
11450: if (wantarray) {
11451: return ($e,$f);
11452: } else {
11453: my $g;
11454: {
11455: use integer;
11456: $g=($e+$f);
11457: if ($_64bit) {
11458: $g=(($g<<32)>>32);
11459: }
11460: }
11461: return $g;
11462: }
11463: }
11464:
1.368 albertel 11465: sub latest_rnd_algorithm_id {
1.675 albertel 11466: return '64bit5';
1.366 albertel 11467: }
1.32 www 11468:
1.503 albertel 11469: sub get_rand_alg {
11470: my ($courseid)=@_;
1.790 albertel 11471: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11472: if ($courseid) {
1.620 albertel 11473: return $env{"course.$courseid.rndseed"};
1.503 albertel 11474: }
11475: return &latest_rnd_algorithm_id();
11476: }
11477:
1.562 albertel 11478: sub validCODE {
11479: my ($CODE)=@_;
11480: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11481: return 0;
11482: }
11483:
1.491 albertel 11484: sub getCODE {
1.620 albertel 11485: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11486: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11487: defined($Apache::lonhomework::parsing_a_task) ) &&
11488: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11489: return $Apache::lonhomework::history{'resource.CODE'};
11490: }
11491: return undef;
11492: }
1.1133 foxr 11493: #
11494: # Determines the random seed for a specific context:
11495: #
11496: # parameters:
11497: # symb - in course context the symb for the seed.
11498: # course_id - The course id of the form domain_coursenum.
11499: # domain - Domain for the user.
11500: # course - Course for the user.
11501: # cenv - environment of the course.
11502: #
11503: # NOTE:
11504: # All parameters are picked out of the environment if missing
11505: # or not defined.
11506: # If a symb cannot be determined the current time is used instead.
11507: #
11508: # For a given well defined symb, courside, domain, username,
11509: # and course environment, the seed is reproducible.
11510: #
1.31 www 11511: sub rndseed {
1.1133 foxr 11512: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11513: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11514: if (!defined($symb)) {
1.366 albertel 11515: unless ($symb=$wsymb) { return time; }
11516: }
1.1146 foxr 11517: if (!defined $courseid) {
11518: $courseid=$wcourseid;
11519: }
11520: if (!defined $domain) { $domain=$wdomain; }
11521: if (!defined $username) { $username=$wusername }
1.1133 foxr 11522:
11523: my $which;
11524: if (defined($cenv->{'rndseed'})) {
11525: $which = $cenv->{'rndseed'};
11526: } else {
11527: $which =&get_rand_alg($courseid);
11528: }
1.491 albertel 11529: if (defined(&getCODE())) {
1.675 albertel 11530: if ($which eq '64bit5') {
11531: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11532: } elsif ($which eq '64bit4') {
1.575 albertel 11533: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11534: } else {
11535: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11536: }
1.675 albertel 11537: } elsif ($which eq '64bit5') {
11538: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11539: } elsif ($which eq '64bit4') {
11540: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11541: } elsif ($which eq '64bit3') {
11542: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11543: } elsif ($which eq '64bit2') {
11544: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11545: } elsif ($which eq '64bit') {
11546: return &rndseed_64bit($symb,$courseid,$domain,$username);
11547: }
11548: return &rndseed_32bit($symb,$courseid,$domain,$username);
11549: }
11550:
11551: sub rndseed_32bit {
11552: my ($symb,$courseid,$domain,$username)=@_;
11553: {
11554: use integer;
11555: my $symbchck=unpack("%32C*",$symb) << 27;
11556: my $symbseed=numval($symb) << 22;
11557: my $namechck=unpack("%32C*",$username) << 17;
11558: my $nameseed=numval($username) << 12;
11559: my $domainseed=unpack("%32C*",$domain) << 7;
11560: my $courseseed=unpack("%32C*",$courseid);
11561: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11562: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11563: #&logthis("rndseed :$num:$symb");
1.564 albertel 11564: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11565: return $num;
11566: }
11567: }
11568:
11569: sub rndseed_64bit {
11570: my ($symb,$courseid,$domain,$username)=@_;
11571: {
11572: use integer;
11573: my $symbchck=unpack("%32S*",$symb) << 21;
11574: my $symbseed=numval($symb) << 10;
11575: my $namechck=unpack("%32S*",$username);
11576:
11577: my $nameseed=numval($username) << 21;
11578: my $domainseed=unpack("%32S*",$domain) << 10;
11579: my $courseseed=unpack("%32S*",$courseid);
11580:
11581: my $num1=$symbchck+$symbseed+$namechck;
11582: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11583: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11584: #&logthis("rndseed :$num:$symb");
1.564 albertel 11585: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11586: return "$num1,$num2";
1.155 albertel 11587: }
1.366 albertel 11588: }
11589:
1.443 albertel 11590: sub rndseed_64bit2 {
11591: my ($symb,$courseid,$domain,$username)=@_;
11592: {
11593: use integer;
11594: # strings need to be an even # of cahracters long, it it is odd the
11595: # last characters gets thrown away
11596: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11597: my $symbseed=numval($symb) << 10;
11598: my $namechck=unpack("%32S*",$username.' ');
11599:
11600: my $nameseed=numval($username) << 21;
1.501 albertel 11601: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11602: my $courseseed=unpack("%32S*",$courseid.' ');
11603:
11604: my $num1=$symbchck+$symbseed+$namechck;
11605: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11606: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11607: #&logthis("rndseed :$num:$symb");
1.803 albertel 11608: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11609: return "$num1,$num2";
11610: }
11611: }
11612:
11613: sub rndseed_64bit3 {
11614: my ($symb,$courseid,$domain,$username)=@_;
11615: {
11616: use integer;
11617: # strings need to be an even # of cahracters long, it it is odd the
11618: # last characters gets thrown away
11619: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11620: my $symbseed=numval2($symb) << 10;
11621: my $namechck=unpack("%32S*",$username.' ');
11622:
11623: my $nameseed=numval2($username) << 21;
1.443 albertel 11624: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11625: my $courseseed=unpack("%32S*",$courseid.' ');
11626:
11627: my $num1=$symbchck+$symbseed+$namechck;
11628: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11629: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11630: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11631: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11632:
1.503 albertel 11633: return "$num1:$num2";
1.443 albertel 11634: }
11635: }
11636:
1.575 albertel 11637: sub rndseed_64bit4 {
11638: my ($symb,$courseid,$domain,$username)=@_;
11639: {
11640: use integer;
11641: # strings need to be an even # of cahracters long, it it is odd the
11642: # last characters gets thrown away
11643: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11644: my $symbseed=numval3($symb) << 10;
11645: my $namechck=unpack("%32S*",$username.' ');
11646:
11647: my $nameseed=numval3($username) << 21;
11648: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11649: my $courseseed=unpack("%32S*",$courseid.' ');
11650:
11651: my $num1=$symbchck+$symbseed+$namechck;
11652: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11653: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11654: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11655: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11656:
1.575 albertel 11657: return "$num1:$num2";
11658: }
11659: }
11660:
1.675 albertel 11661: sub rndseed_64bit5 {
11662: my ($symb,$courseid,$domain,$username)=@_;
11663: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11664: return "$num1:$num2";
11665: }
11666:
1.366 albertel 11667: sub rndseed_CODE_64bit {
11668: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11669: {
1.366 albertel 11670: use integer;
1.443 albertel 11671: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11672: my $symbseed=numval2($symb);
1.491 albertel 11673: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11674: my $CODEseed=numval(&getCODE());
1.443 albertel 11675: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11676: my $num1=$symbseed+$CODEchck;
11677: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11678: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11679: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11680: if ($_64bit) { $num1=(($num1<<32)>>32); }
11681: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11682: return "$num1:$num2";
1.366 albertel 11683: }
11684: }
11685:
1.575 albertel 11686: sub rndseed_CODE_64bit4 {
11687: my ($symb,$courseid,$domain,$username)=@_;
11688: {
11689: use integer;
11690: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11691: my $symbseed=numval3($symb);
11692: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11693: my $CODEseed=numval3(&getCODE());
11694: my $courseseed=unpack("%32S*",$courseid.' ');
11695: my $num1=$symbseed+$CODEchck;
11696: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11697: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11698: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11699: if ($_64bit) { $num1=(($num1<<32)>>32); }
11700: if ($_64bit) { $num2=(($num2<<32)>>32); }
11701: return "$num1:$num2";
11702: }
11703: }
11704:
1.675 albertel 11705: sub rndseed_CODE_64bit5 {
11706: my ($symb,$courseid,$domain,$username)=@_;
11707: my $code = &getCODE();
11708: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11709: return "$num1:$num2";
11710: }
11711:
1.366 albertel 11712: sub setup_random_from_rndseed {
11713: my ($rndseed)=@_;
1.503 albertel 11714: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 11715: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11716: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11717: &Math::Random::random_set_seed_from_phrase($rndseed);
11718: } else {
11719: &Math::Random::random_set_seed($num1,$num2);
11720: }
1.366 albertel 11721: } else {
11722: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11723: }
1.36 albertel 11724: }
11725:
1.474 albertel 11726: sub latest_receipt_algorithm_id {
1.835 albertel 11727: return 'receipt3';
1.474 albertel 11728: }
11729:
1.480 www 11730: sub recunique {
11731: my $fucourseid=shift;
11732: my $unique;
1.835 albertel 11733: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11734: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11735: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11736: } else {
11737: $unique=$perlvar{'lonReceipt'};
11738: }
11739: return unpack("%32C*",$unique);
11740: }
11741:
11742: sub recprefix {
11743: my $fucourseid=shift;
11744: my $prefix;
1.835 albertel 11745: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11746: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11747: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11748: } else {
11749: $prefix=$perlvar{'lonHostID'};
11750: }
11751: return unpack("%32C*",$prefix);
11752: }
11753:
1.76 www 11754: sub ireceipt {
1.474 albertel 11755: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11756:
11757: my $return =&recprefix($fucourseid).'-';
11758:
11759: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11760: $env{'request.state'} eq 'construct') {
11761: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11762: return $return;
11763: }
11764:
1.76 www 11765: my $cuname=unpack("%32C*",$funame);
11766: my $cudom=unpack("%32C*",$fudom);
11767: my $cucourseid=unpack("%32C*",$fucourseid);
11768: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11769: my $cunique=&recunique($fucourseid);
1.474 albertel 11770: my $cpart=unpack("%32S*",$part);
1.835 albertel 11771: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11772:
1.790 albertel 11773: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11774:
11775: $return.= ($cunique%$cuname+
11776: $cunique%$cudom+
11777: $cusymb%$cuname+
11778: $cusymb%$cudom+
11779: $cucourseid%$cuname+
11780: $cucourseid%$cudom+
11781: $cpart%$cuname+
11782: $cpart%$cudom);
11783: } else {
11784: $return.= ($cunique%$cuname+
11785: $cunique%$cudom+
11786: $cusymb%$cuname+
11787: $cusymb%$cudom+
11788: $cucourseid%$cuname+
11789: $cucourseid%$cudom);
11790: }
11791: return $return;
1.76 www 11792: }
11793:
11794: sub receipt {
1.474 albertel 11795: my ($part)=@_;
1.790 albertel 11796: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11797: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11798: }
1.260 ng 11799:
1.790 albertel 11800: sub whichuser {
11801: my ($passedsymb)=@_;
11802: my ($symb,$courseid,$domain,$name,$publicuser);
11803: if (defined($env{'form.grade_symb'})) {
11804: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11805: my $allowed=&allowed('vgr',$tmp_courseid);
11806: if (!$allowed &&
11807: exists($env{'request.course.sec'}) &&
11808: $env{'request.course.sec'} !~ /^\s*$/) {
11809: $allowed=&allowed('vgr',$tmp_courseid.
11810: '/'.$env{'request.course.sec'});
11811: }
11812: if ($allowed) {
11813: ($symb)=&get_env_multiple('form.grade_symb');
11814: $courseid=$tmp_courseid;
11815: ($domain)=&get_env_multiple('form.grade_domain');
11816: ($name)=&get_env_multiple('form.grade_username');
11817: return ($symb,$courseid,$domain,$name,$publicuser);
11818: }
11819: }
11820: if (!$passedsymb) {
11821: $symb=&symbread();
11822: } else {
11823: $symb=$passedsymb;
11824: }
11825: $courseid=$env{'request.course.id'};
11826: $domain=$env{'user.domain'};
11827: $name=$env{'user.name'};
11828: if ($name eq 'public' && $domain eq 'public') {
11829: if (!defined($env{'form.username'})) {
11830: $env{'form.username'}.=time.rand(10000000);
11831: }
11832: $name.=$env{'form.username'};
11833: }
11834: return ($symb,$courseid,$domain,$name,$publicuser);
11835:
11836: }
11837:
1.36 albertel 11838: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11839: # returns either the contents of the file or
11840: # -1 if the file doesn't exist
1.481 raeburn 11841: #
11842: # if the target is a file that was uploaded via DOCS,
11843: # a check will be made to see if a current copy exists on the local server,
11844: # if it does this will be served, otherwise a copy will be retrieved from
11845: # the home server for the course and stored in /home/httpd/html/userfiles on
11846: # the local server.
1.472 albertel 11847:
1.36 albertel 11848: sub getfile {
1.538 albertel 11849: my ($file) = @_;
1.609 banghart 11850: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11851: &repcopy($file);
11852: return &readfile($file);
11853: }
11854:
11855: sub repcopy_userfile {
11856: my ($file)=@_;
1.1142 raeburn 11857: my $londocroot = $perlvar{'lonDocRoot'};
11858: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11859: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11860: my ($cdom,$cnum,$filename) =
1.811 albertel 11861: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11862: my $uri="/uploaded/$cdom/$cnum/$filename";
11863: if (-e "$file") {
1.828 www 11864: # we already have a local copy, check it out
1.538 albertel 11865: my @fileinfo = stat($file);
1.828 www 11866: my $rtncode;
11867: my $info;
1.538 albertel 11868: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11869: if ($lwpresp ne 'ok') {
1.828 www 11870: # there is no such file anymore, even though we had a local copy
1.482 albertel 11871: if ($rtncode eq '404') {
1.538 albertel 11872: unlink($file);
1.482 albertel 11873: }
11874: return -1;
11875: }
11876: if ($info < $fileinfo[9]) {
1.828 www 11877: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11878: return 'ok';
1.828 www 11879: } else {
11880: # the file is outdated, get rid of it
11881: unlink($file);
1.482 albertel 11882: }
1.828 www 11883: }
11884: # one way or the other, at this point, we don't have the file
11885: # construct the correct path for the file
11886: my @parts = ($cdom,$cnum);
11887: if ($filename =~ m|^(.+)/[^/]+$|) {
11888: push @parts, split(/\//,$1);
11889: }
11890: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11891: foreach my $part (@parts) {
11892: $path .= '/'.$part;
11893: if (!-e $path) {
11894: mkdir($path,0770);
1.482 albertel 11895: }
11896: }
1.828 www 11897: # now the path exists for sure
11898: # get a user agent
11899: my $ua=new LWP::UserAgent;
11900: my $transferfile=$file.'.in.transfer';
11901: # FIXME: this should flock
11902: if (-e $transferfile) { return 'ok'; }
11903: my $request;
11904: $uri=~s/^\///;
1.980 raeburn 11905: my $homeserver = &homeserver($cnum,$cdom);
11906: my $protocol = $protocol{$homeserver};
11907: $protocol = 'http' if ($protocol ne 'https');
11908: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11909: my $response=$ua->request($request,$transferfile);
11910: # did it work?
11911: if ($response->is_error()) {
11912: unlink($transferfile);
11913: &logthis("Userfile repcopy failed for $uri");
11914: return -1;
11915: }
11916: # worked, rename the transfer file
11917: rename($transferfile,$file);
1.607 raeburn 11918: return 'ok';
1.481 raeburn 11919: }
11920:
1.517 albertel 11921: sub tokenwrapper {
11922: my $uri=shift;
1.980 raeburn 11923: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11924: $uri=~s|^/||;
1.620 albertel 11925: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11926: my $token=$1;
1.552 albertel 11927: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11928: if ($udom && $uname && $file) {
11929: $file=~s|(\?\.*)*$||;
1.949 raeburn 11930: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11931: my $homeserver = &homeserver($uname,$udom);
11932: my $protocol = $protocol{$homeserver};
11933: $protocol = 'http' if ($protocol ne 'https');
11934: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11935: (($uri=~/\?/)?'&':'?').'token='.$token.
11936: '&tokenissued='.$perlvar{'lonHostID'};
11937: } else {
11938: return '/adm/notfound.html';
11939: }
11940: }
11941:
1.828 www 11942: # call with reqtype HEAD: get last modification time
11943: # call with reqtype GET: get the file contents
11944: # Do not call this with reqtype GET for large files! It loads everything into memory
11945: #
1.481 raeburn 11946: sub getuploaded {
11947: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11948: $uri=~s/^\///;
1.980 raeburn 11949: my $homeserver = &homeserver($cnum,$cdom);
11950: my $protocol = $protocol{$homeserver};
11951: $protocol = 'http' if ($protocol ne 'https');
11952: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11953: my $ua=new LWP::UserAgent;
11954: my $request=new HTTP::Request($reqtype,$uri);
11955: my $response=$ua->request($request);
11956: $$rtncode = $response->code;
1.482 albertel 11957: if (! $response->is_success()) {
11958: return 'failed';
11959: }
11960: if ($reqtype eq 'HEAD') {
1.486 www 11961: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11962: } elsif ($reqtype eq 'GET') {
11963: $$info = $response->content;
1.472 albertel 11964: }
1.482 albertel 11965: return 'ok';
1.36 albertel 11966: }
11967:
1.481 raeburn 11968: sub readfile {
11969: my $file = shift;
11970: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11971: my $fh;
11972: open($fh,"<$file");
11973: my $a='';
1.800 albertel 11974: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11975: return $a;
11976: }
11977:
1.36 albertel 11978: sub filelocation {
1.590 banghart 11979: my ($dir,$file) = @_;
11980: my $location;
11981: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11982:
11983: if ($file =~ m-^/adm/-) {
11984: $file=~s-^/adm/wrapper/-/-;
11985: $file=~s-^/adm/coursedocs/showdoc/-/-;
11986: }
1.882 albertel 11987:
1.1139 www 11988: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11989: $location = $file;
1.609 banghart 11990: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11991: my ($udom,$uname,$filename)=
1.811 albertel 11992: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11993: my $home=&homeserver($uname,$udom);
11994: my $is_me=0;
11995: my @ids=¤t_machine_ids();
11996: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11997: if ($is_me) {
1.1117 foxr 11998: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11999: } else {
12000: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12001: $udom.'/'.$uname.'/'.$filename;
12002: }
1.882 albertel 12003: } elsif ($file =~ m-^/adm/-) {
12004: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 12005: } else {
12006: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12007: $file=~s:^/(res|priv)/:/:;
12008: my $space=$1;
1.590 banghart 12009: if ( !( $file =~ m:^/:) ) {
12010: $location = $dir. '/'.$file;
12011: } else {
1.1142 raeburn 12012: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12013: }
1.59 albertel 12014: }
1.590 banghart 12015: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12016: while ($location=~m{/\.\./}) {
12017: if ($location =~ m{/[^/]+/\.\./}) {
12018: $location=~ s{/[^/]+/\.\./}{/}g;
12019: } else {
12020: $location=~ s{/\.\./}{/}g;
12021: }
12022: } #remove dir/..
1.590 banghart 12023: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12024: return $location;
1.46 www 12025: }
1.36 albertel 12026:
1.46 www 12027: sub hreflocation {
12028: my ($dir,$file)=@_;
1.980 raeburn 12029: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12030: $file=filelocation($dir,$file);
1.700 albertel 12031: } elsif ($file=~m-^/adm/-) {
12032: $file=~s-^/adm/wrapper/-/-;
12033: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12034: }
12035: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12036: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12037: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12038: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12039: {/uploaded/$1/$2/}x;
1.46 www 12040: }
1.913 albertel 12041: if ($file=~ m{^/userfiles/}) {
12042: $file =~ s{^/userfiles/}{/uploaded/};
12043: }
1.462 albertel 12044: return $file;
1.465 albertel 12045: }
12046:
1.1139 www 12047:
12048:
12049:
12050:
1.465 albertel 12051: sub current_machine_domains {
1.853 albertel 12052: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12053: }
12054:
12055: sub machine_domains {
12056: my ($hostname) = @_;
1.465 albertel 12057: my @domains;
1.838 albertel 12058: my %hostname = &all_hostnames();
1.465 albertel 12059: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12060: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12061: if ($hostname eq $name) {
1.844 albertel 12062: push(@domains,&host_domain($id));
1.465 albertel 12063: }
12064: }
12065: return @domains;
12066: }
12067:
12068: sub current_machine_ids {
1.853 albertel 12069: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12070: }
12071:
12072: sub machine_ids {
12073: my ($hostname) = @_;
12074: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12075: my @ids;
1.888 albertel 12076: my %name_to_host = &all_names();
1.889 albertel 12077: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12078: return @{ $name_to_host{$hostname} };
12079: }
12080: return;
1.31 www 12081: }
12082:
1.824 raeburn 12083: sub additional_machine_domains {
12084: my @domains;
12085: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12086: while( my $line = <$fh>) {
12087: $line =~ s/\s//g;
12088: push(@domains,$line);
12089: }
12090: return @domains;
12091: }
12092:
12093: sub default_login_domain {
12094: my $domain = $perlvar{'lonDefDomain'};
12095: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12096: foreach my $posdom (¤t_machine_domains(),
12097: &additional_machine_domains()) {
12098: if (lc($posdom) eq lc($testdomain)) {
12099: $domain=$posdom;
12100: last;
12101: }
12102: }
12103: return $domain;
12104: }
12105:
1.31 www 12106: # ------------------------------------------------------------- Declutters URLs
12107:
12108: sub declutter {
12109: my $thisfn=shift;
1.569 albertel 12110: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 12111: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12112: $thisfn=~s{^/home/httpd/html}{};
12113: }
1.31 www 12114: $thisfn=~s/^\///;
1.697 albertel 12115: $thisfn=~s|^adm/wrapper/||;
12116: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12117: $thisfn=~s/^res\///;
1.1172 bisitz 12118: $thisfn=~s/^priv\///;
1.1032 raeburn 12119: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12120: $thisfn=~s/\?.+$//;
12121: }
1.268 www 12122: return $thisfn;
12123: }
12124:
12125: # ------------------------------------------------------------- Clutter up URLs
12126:
12127: sub clutter {
12128: my $thisfn='/'.&declutter(shift);
1.887 albertel 12129: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12130: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12131: $thisfn='/res'.$thisfn;
12132: }
1.1031 raeburn 12133: if ($thisfn !~m|^/adm|) {
12134: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12135: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12136: } else {
12137: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12138: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12139: if ($embstyle eq 'ssi'
12140: || ($embstyle eq 'hdn')
12141: || ($embstyle eq 'rat')
12142: || ($embstyle eq 'prv')
12143: || ($embstyle eq 'ign')) {
12144: #do nothing with these
12145: } elsif (($embstyle eq 'img')
1.695 albertel 12146: || ($embstyle eq 'emb')
12147: || ($embstyle eq 'wrp')) {
12148: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12149: } elsif ($embstyle eq 'unk'
12150: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12151: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12152: } else {
1.718 www 12153: # &logthis("Got a blank emb style");
1.695 albertel 12154: }
1.694 albertel 12155: }
12156: }
1.31 www 12157: return $thisfn;
1.12 www 12158: }
12159:
1.787 albertel 12160: sub clutter_with_no_wrapper {
12161: my $uri = &clutter(shift);
12162: if ($uri =~ m-^/adm/-) {
12163: $uri =~ s-^/adm/wrapper/-/-;
12164: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12165: }
12166: return $uri;
12167: }
12168:
1.557 albertel 12169: sub freeze_escape {
12170: my ($value)=@_;
12171: if (ref($value)) {
12172: $value=&nfreeze($value);
12173: return '__FROZEN__'.&escape($value);
12174: }
12175: return &escape($value);
12176: }
12177:
1.11 www 12178:
1.557 albertel 12179: sub thaw_unescape {
12180: my ($value)=@_;
12181: if ($value =~ /^__FROZEN__/) {
12182: substr($value,0,10,undef);
12183: $value=&unescape($value);
12184: return &thaw($value);
12185: }
12186: return &unescape($value);
12187: }
12188:
1.436 albertel 12189: sub correct_line_ends {
12190: my ($result)=@_;
12191: $$result =~s/\r\n/\n/mg;
12192: $$result =~s/\r/\n/mg;
1.415 albertel 12193: }
1.1 albertel 12194: # ================================================================ Main Program
12195:
1.184 www 12196: sub goodbye {
1.204 albertel 12197: &logthis("Starting Shut down");
1.443 albertel 12198: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12199: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12200: #converted
1.599 albertel 12201: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12202: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12203: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12204: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12205: #1.1 only
1.870 albertel 12206: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12207: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12208: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12209: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12210: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12211: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12212: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12213: &flushcourselogs();
12214: &logthis("Shutting down");
12215: }
12216:
1.852 albertel 12217: sub get_dns {
1.1172.2.17 raeburn 12218: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12219: if (!$ignore_cache) {
12220: my ($content,$cached)=
12221: &Apache::lonnet::is_cached_new('dns',$url);
12222: if ($cached) {
1.1172.2.17 raeburn 12223: &$func($content,$hashref);
1.869 albertel 12224: return;
12225: }
12226: }
12227:
12228: my %alldns;
1.852 albertel 12229: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12230: foreach my $dns (<$config>) {
12231: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12232: my $line = $1;
12233: my ($host,$protocol) = split(/:/,$line);
12234: if ($protocol ne 'https') {
12235: $protocol = 'http';
12236: }
12237: $alldns{$host} = $protocol;
1.869 albertel 12238: }
12239: while (%alldns) {
1.1172.2.52 raeburn 12240: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12241: my $ua=new LWP::UserAgent;
1.1134 raeburn 12242: $ua->timeout(30);
1.979 raeburn 12243: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12244: my $response=$ua->request($request);
1.979 raeburn 12245: delete($alldns{$dns});
1.852 albertel 12246: next if ($response->is_error());
12247: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 12248: unless ($nocache) {
1.1172.2.23 raeburn 12249: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 12250: }
12251: &$func(\@content,$hashref);
1.869 albertel 12252: return;
1.852 albertel 12253: }
12254: close($config);
1.871 albertel 12255: my $which = (split('/',$url))[3];
12256: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12257: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12258: my @content = <$config>;
1.1172.2.17 raeburn 12259: &$func(\@content,$hashref);
12260: return;
12261: }
12262:
12263: # ------------------------------------------------------Get DNS checksums file
12264: sub parse_dns_checksums_tab {
12265: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 12266: my $lonhost = $perlvar{'lonHostID'};
12267: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 12268: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 12269: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12270: my $webconfdir = '/etc/httpd/conf';
12271: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12272: $webconfdir = '/etc/apache2';
12273: } elsif ($distro =~ /^sles(\d+)$/) {
12274: if ($1 >= 10) {
12275: $webconfdir = '/etc/apache2';
12276: }
12277: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12278: if ($1 >= 10.0) {
12279: $webconfdir = '/etc/apache2';
12280: }
12281: }
1.1172.2.17 raeburn 12282: my ($release,$timestamp) = split(/\-/,$loncaparev);
12283: my (%chksum,%revnum);
12284: if (ref($lines) eq 'ARRAY') {
12285: chomp(@{$lines});
1.1172.2.34 raeburn 12286: my $version = shift(@{$lines});
12287: if ($version eq $release) {
1.1172.2.17 raeburn 12288: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 12289: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 12290: if ($file =~ m{^/etc/httpd/conf}) {
12291: if ($webconfdir eq '/etc/apache2') {
12292: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12293: }
12294: }
1.1172.2.34 raeburn 12295: $chksum{$file} = $shasum;
12296: $revnum{$file} = $version;
1.1172.2.17 raeburn 12297: }
12298: if (ref($hashref) eq 'HASH') {
12299: %{$hashref} = (
12300: sums => \%chksum,
12301: versions => \%revnum,
12302: );
12303: }
12304: }
12305: }
1.869 albertel 12306: return;
1.852 albertel 12307: }
1.1172.2.17 raeburn 12308:
12309: sub fetch_dns_checksums {
12310: my %checksums;
1.1172.2.34 raeburn 12311: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 12312: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 12313: my ($release,$timestamp) = split(/\-/,$loncaparev);
12314: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 12315: \%checksums);
12316: return \%checksums;
12317: }
12318:
1.327 albertel 12319: # ------------------------------------------------------------ Read domain file
12320: {
1.852 albertel 12321: my $loaded;
1.846 albertel 12322: my %domain;
12323:
1.852 albertel 12324: sub parse_domain_tab {
12325: my ($lines) = @_;
12326: foreach my $line (@$lines) {
12327: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12328:
1.846 albertel 12329: chomp($line);
1.852 albertel 12330: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12331: my %this_domain;
12332: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12333: 'lang_def', 'city', 'longi', 'lati',
12334: 'primary') {
12335: $this_domain{$field} = shift(@elements);
12336: }
12337: $domain{$name} = \%this_domain;
1.852 albertel 12338: }
12339: }
1.864 albertel 12340:
12341: sub reset_domain_info {
12342: undef($loaded);
12343: undef(%domain);
12344: }
12345:
1.852 albertel 12346: sub load_domain_tab {
1.1172.2.70 raeburn 12347: my ($ignore_cache,$nocache) = @_;
12348: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 12349: my $fh;
12350: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12351: my @lines = <$fh>;
12352: &parse_domain_tab(\@lines);
1.448 albertel 12353: }
1.852 albertel 12354: close($fh);
12355: $loaded = 1;
1.327 albertel 12356: }
1.846 albertel 12357:
12358: sub domain {
1.852 albertel 12359: &load_domain_tab() if (!$loaded);
12360:
1.846 albertel 12361: my ($name,$what) = @_;
12362: return if ( !exists($domain{$name}) );
12363:
12364: if (!$what) {
12365: return $domain{$name}{'description'};
12366: }
12367: return $domain{$name}{$what};
12368: }
1.974 raeburn 12369:
12370: sub domain_info {
12371: &load_domain_tab() if (!$loaded);
12372: return %domain;
12373: }
12374:
1.327 albertel 12375: }
12376:
12377:
1.1 albertel 12378: # ------------------------------------------------------------- Read hosts file
12379: {
1.838 albertel 12380: my %hostname;
1.844 albertel 12381: my %hostdom;
1.845 albertel 12382: my %libserv;
1.852 albertel 12383: my $loaded;
1.888 albertel 12384: my %name_to_host;
1.1074 raeburn 12385: my %internetdom;
1.1107 raeburn 12386: my %LC_dns_serv;
1.852 albertel 12387:
12388: sub parse_hosts_tab {
12389: my ($file) = @_;
12390: foreach my $configline (@$file) {
12391: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12392: chomp($configline);
12393: if ($configline =~ /^\^/) {
12394: if ($configline =~ /^\^([\w.\-]+)/) {
12395: $LC_dns_serv{$1} = 1;
12396: }
12397: next;
12398: }
1.1074 raeburn 12399: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12400: $name=~s/\s//g;
12401: if ($id && $domain && $role && $name) {
12402: $hostname{$id}=$name;
1.888 albertel 12403: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12404: $hostdom{$id}=$domain;
12405: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12406: if (defined($protocol)) {
12407: if ($protocol eq 'https') {
12408: $protocol{$id} = $protocol;
12409: } else {
12410: $protocol{$id} = 'http';
12411: }
1.968 raeburn 12412: } else {
1.969 raeburn 12413: $protocol{$id} = 'http';
1.968 raeburn 12414: }
1.1074 raeburn 12415: if (defined($intdom)) {
12416: $internetdom{$id} = $intdom;
12417: }
1.852 albertel 12418: }
12419: }
12420: }
1.864 albertel 12421:
12422: sub reset_hosts_info {
1.897 albertel 12423: &purge_remembered();
1.864 albertel 12424: &reset_domain_info();
12425: &reset_hosts_ip_info();
1.892 albertel 12426: undef(%name_to_host);
1.864 albertel 12427: undef(%hostname);
12428: undef(%hostdom);
12429: undef(%libserv);
12430: undef($loaded);
12431: }
1.1 albertel 12432:
1.852 albertel 12433: sub load_hosts_tab {
1.1172.2.70 raeburn 12434: my ($ignore_cache,$nocache) = @_;
12435: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852 albertel 12436: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12437: my @config = <$config>;
12438: &parse_hosts_tab(\@config);
12439: close($config);
12440: $loaded=1;
1.1 albertel 12441: }
1.852 albertel 12442:
1.838 albertel 12443: sub hostname {
1.852 albertel 12444: &load_hosts_tab() if (!$loaded);
12445:
1.838 albertel 12446: my ($lonid) = @_;
12447: return $hostname{$lonid};
12448: }
1.845 albertel 12449:
1.838 albertel 12450: sub all_hostnames {
1.852 albertel 12451: &load_hosts_tab() if (!$loaded);
12452:
1.838 albertel 12453: return %hostname;
12454: }
1.845 albertel 12455:
1.888 albertel 12456: sub all_names {
1.1172.2.70 raeburn 12457: my ($ignore_cache,$nocache) = @_;
12458: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 12459:
12460: return %name_to_host;
12461: }
12462:
1.974 raeburn 12463: sub all_host_domain {
12464: &load_hosts_tab() if (!$loaded);
12465: return %hostdom;
12466: }
12467:
1.845 albertel 12468: sub is_library {
1.852 albertel 12469: &load_hosts_tab() if (!$loaded);
12470:
1.845 albertel 12471: return exists($libserv{$_[0]});
12472: }
12473:
12474: sub all_library {
1.852 albertel 12475: &load_hosts_tab() if (!$loaded);
12476:
1.845 albertel 12477: return %libserv;
12478: }
12479:
1.1062 droeschl 12480: sub unique_library {
12481: #2x reverse removes all hostnames that appear more than once
12482: my %unique = reverse &all_library();
12483: return reverse %unique;
12484: }
12485:
1.841 albertel 12486: sub get_servers {
1.852 albertel 12487: &load_hosts_tab() if (!$loaded);
12488:
1.841 albertel 12489: my ($domain,$type) = @_;
12490: my %possible_hosts = ($type eq 'library') ? %libserv
12491: : %hostname;
12492: my %result;
1.842 albertel 12493: if (ref($domain) eq 'ARRAY') {
12494: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12495: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12496: $result{$host} = $hostname;
12497: }
12498: }
12499: } else {
12500: while ( my ($host,$hostname) = each(%possible_hosts)) {
12501: if ($hostdom{$host} eq $domain) {
12502: $result{$host} = $hostname;
12503: }
1.841 albertel 12504: }
12505: }
12506: return %result;
12507: }
1.845 albertel 12508:
1.1062 droeschl 12509: sub get_unique_servers {
12510: my %unique = reverse &get_servers(@_);
12511: return reverse %unique;
12512: }
12513:
1.844 albertel 12514: sub host_domain {
1.852 albertel 12515: &load_hosts_tab() if (!$loaded);
12516:
1.844 albertel 12517: my ($lonid) = @_;
12518: return $hostdom{$lonid};
12519: }
12520:
1.841 albertel 12521: sub all_domains {
1.852 albertel 12522: &load_hosts_tab() if (!$loaded);
12523:
1.841 albertel 12524: my %seen;
12525: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12526: return @uniq;
12527: }
1.1074 raeburn 12528:
12529: sub internet_dom {
12530: &load_hosts_tab() if (!$loaded);
12531:
12532: my ($lonid) = @_;
12533: return $internetdom{$lonid};
12534: }
1.1107 raeburn 12535:
12536: sub is_LC_dns {
12537: &load_hosts_tab() if (!$loaded);
12538:
12539: my ($hostname) = @_;
12540: return exists($LC_dns_serv{$hostname});
12541: }
12542:
1.1 albertel 12543: }
12544:
1.847 albertel 12545: {
12546: my %iphost;
1.856 albertel 12547: my %name_to_ip;
12548: my %lonid_to_ip;
1.869 albertel 12549:
1.847 albertel 12550: sub get_hosts_from_ip {
12551: my ($ip) = @_;
12552: my %iphosts = &get_iphost();
12553: if (ref($iphosts{$ip})) {
12554: return @{$iphosts{$ip}};
12555: }
12556: return;
1.839 albertel 12557: }
1.864 albertel 12558:
12559: sub reset_hosts_ip_info {
12560: undef(%iphost);
12561: undef(%name_to_ip);
12562: undef(%lonid_to_ip);
12563: }
1.856 albertel 12564:
12565: sub get_host_ip {
12566: my ($lonid) = @_;
12567: if (exists($lonid_to_ip{$lonid})) {
12568: return $lonid_to_ip{$lonid};
12569: }
12570: my $name=&hostname($lonid);
12571: my $ip = gethostbyname($name);
12572: return if (!$ip || length($ip) ne 4);
12573: $ip=inet_ntoa($ip);
12574: $name_to_ip{$name} = $ip;
12575: $lonid_to_ip{$lonid} = $ip;
12576: return $ip;
12577: }
1.847 albertel 12578:
12579: sub get_iphost {
1.1172.2.70 raeburn 12580: my ($ignore_cache,$nocache) = @_;
1.894 albertel 12581:
1.869 albertel 12582: if (!$ignore_cache) {
12583: if (%iphost) {
12584: return %iphost;
12585: }
12586: my ($ip_info,$cached)=
12587: &Apache::lonnet::is_cached_new('iphost','iphost');
12588: if ($cached) {
12589: %iphost = %{$ip_info->[0]};
12590: %name_to_ip = %{$ip_info->[1]};
12591: %lonid_to_ip = %{$ip_info->[2]};
12592: return %iphost;
12593: }
12594: }
1.894 albertel 12595:
12596: # get yesterday's info for fallback
12597: my %old_name_to_ip;
12598: my ($ip_info,$cached)=
12599: &Apache::lonnet::is_cached_new('iphost','iphost');
12600: if ($cached) {
12601: %old_name_to_ip = %{$ip_info->[1]};
12602: }
12603:
1.1172.2.70 raeburn 12604: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 12605: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12606: my $ip;
12607: if (!exists($name_to_ip{$name})) {
12608: $ip = gethostbyname($name);
12609: if (!$ip || length($ip) ne 4) {
1.894 albertel 12610: if (defined($old_name_to_ip{$name})) {
12611: $ip = $old_name_to_ip{$name};
12612: &logthis("Can't find $name defaulting to old $ip");
12613: } else {
12614: &logthis("Name $name no IP found");
12615: next;
12616: }
12617: } else {
12618: $ip=inet_ntoa($ip);
1.847 albertel 12619: }
12620: $name_to_ip{$name} = $ip;
12621: } else {
12622: $ip = $name_to_ip{$name};
1.653 albertel 12623: }
1.888 albertel 12624: foreach my $id (@{ $name_to_host{$name} }) {
12625: $lonid_to_ip{$id} = $ip;
12626: }
12627: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12628: }
1.1172.2.70 raeburn 12629: unless ($nocache) {
12630: &do_cache_new('iphost','iphost',
12631: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12632: 48*60*60);
12633: }
1.869 albertel 12634:
1.847 albertel 12635: return %iphost;
1.598 albertel 12636: }
12637:
1.992 raeburn 12638: #
12639: # Given a DNS returns the loncapa host name for that DNS
12640: #
12641: sub host_from_dns {
12642: my ($dns) = @_;
12643: my @hosts;
12644: my $ip;
12645:
1.993 raeburn 12646: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12647: $ip = $name_to_ip{$dns};
12648: }
12649: if (!$ip) {
12650: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12651: if (length($ip) == 4) {
12652: $ip = &IO::Socket::inet_ntoa($ip);
12653: }
12654: }
12655: if ($ip) {
12656: @hosts = get_hosts_from_ip($ip);
12657: return $hosts[0];
12658: }
12659: return undef;
1.986 foxr 12660: }
1.992 raeburn 12661:
1.1074 raeburn 12662: sub get_internet_names {
12663: my ($lonid) = @_;
12664: return if ($lonid eq '');
12665: my ($idnref,$cached)=
12666: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12667: if ($cached) {
12668: return $idnref;
12669: }
12670: my $ip = &get_host_ip($lonid);
12671: my @hosts = &get_hosts_from_ip($ip);
12672: my %iphost = &get_iphost();
12673: my (@idns,%seen);
12674: foreach my $id (@hosts) {
12675: my $dom = &host_domain($id);
12676: my $prim_id = &domain($dom,'primary');
12677: my $prim_ip = &get_host_ip($prim_id);
12678: next if ($seen{$prim_ip});
12679: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12680: foreach my $id (@{$iphost{$prim_ip}}) {
12681: my $intdom = &internet_dom($id);
12682: unless (grep(/^\Q$intdom\E$/,@idns)) {
12683: push(@idns,$intdom);
12684: }
12685: }
12686: }
12687: $seen{$prim_ip} = 1;
12688: }
1.1172.2.23 raeburn 12689: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12690: }
12691:
1.986 foxr 12692: }
12693:
1.1079 raeburn 12694: sub all_loncaparevs {
1.1172.2.39 raeburn 12695: 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 12696: }
12697:
1.1172.2.27 raeburn 12698: # ------------------------------------------------------- Read loncaparev table
12699: {
12700: sub load_loncaparevs {
12701: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12702: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12703: while (my $configline=<$config>) {
12704: chomp($configline);
12705: my ($hostid,$loncaparev)=split(/:/,$configline);
12706: $loncaparevs{$hostid}=$loncaparev;
12707: }
12708: close($config);
12709: }
12710: }
12711: }
12712: }
12713:
12714: # ----------------------------------------------------- Read serverhostID table
12715: {
12716: sub load_serverhomeIDs {
12717: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12718: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12719: while (my $configline=<$config>) {
12720: chomp($configline);
12721: my ($name,$id)=split(/:/,$configline);
12722: $serverhomeIDs{$name}=$id;
12723: }
12724: close($config);
12725: }
12726: }
12727: }
12728: }
12729:
12730:
1.862 albertel 12731: BEGIN {
12732:
12733: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12734: unless ($readit) {
12735: {
12736: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12737: %perlvar = (%perlvar,%{$configvars});
12738: }
12739:
12740:
1.1 albertel 12741: # ------------------------------------------------------ Read spare server file
12742: {
1.448 albertel 12743: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12744:
12745: while (my $configline=<$config>) {
12746: chomp($configline);
1.284 matthew 12747: if ($configline) {
1.784 albertel 12748: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12749: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12750: push(@{ $spareid{$type} }, $host);
1.1 albertel 12751: }
12752: }
1.448 albertel 12753: close($config);
1.1 albertel 12754: }
1.11 www 12755: # ------------------------------------------------------------ Read permissions
12756: {
1.448 albertel 12757: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12758:
12759: while (my $configline=<$config>) {
1.448 albertel 12760: chomp($configline);
12761: if ($configline) {
12762: my ($role,$perm)=split(/ /,$configline);
12763: if ($perm ne '') { $pr{$role}=$perm; }
12764: }
1.11 www 12765: }
1.448 albertel 12766: close($config);
1.11 www 12767: }
12768:
12769: # -------------------------------------------- Read plain texts for permissions
12770: {
1.448 albertel 12771: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12772:
12773: while (my $configline=<$config>) {
1.448 albertel 12774: chomp($configline);
12775: if ($configline) {
1.742 raeburn 12776: my ($short,@plain)=split(/:/,$configline);
12777: %{$prp{$short}} = ();
12778: if (@plain > 0) {
12779: $prp{$short}{'std'} = $plain[0];
12780: for (my $i=1; $i<@plain; $i++) {
12781: $prp{$short}{'alt'.$i} = $plain[$i];
12782: }
12783: }
1.448 albertel 12784: }
1.135 www 12785: }
1.448 albertel 12786: close($config);
1.135 www 12787: }
12788:
12789: # ---------------------------------------------------------- Read package table
12790: {
1.448 albertel 12791: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12792:
12793: while (my $configline=<$config>) {
1.483 albertel 12794: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12795: chomp($configline);
12796: my ($short,$plain)=split(/:/,$configline);
12797: my ($pack,$name)=split(/\&/,$short);
12798: if ($plain ne '') {
12799: $packagetab{$pack.'&'.$name.'&name'}=$name;
12800: $packagetab{$short}=$plain;
12801: }
1.11 www 12802: }
1.448 albertel 12803: close($config);
1.329 matthew 12804: }
12805:
1.1172.2.27 raeburn 12806: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 12807:
1.1172.2.27 raeburn 12808: &load_loncaparevs();
12809:
12810: # ------------------------------------------------------- Read serverhostID table
12811:
12812: &load_serverhomeIDs();
1.1074 raeburn 12813:
1.1172.2.27 raeburn 12814: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12815: {
12816: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12817: if (-e $file) {
12818: my $parser = HTML::LCParser->new($file);
12819: while (my $token = $parser->get_token()) {
12820: if ($token->[0] eq 'S') {
12821: my $item = $token->[1];
12822: my $name = $token->[2]{'name'};
12823: my $value = $token->[2]{'value'};
12824: if ($item ne '' && $name ne '' && $value ne '') {
12825: my $release = $parser->get_text();
12826: $release =~ s/(^\s*|\s*$ )//gx;
12827: $needsrelease{$item.':'.$name.':'.$value} = $release;
12828: }
12829: }
12830: }
12831: }
1.1073 raeburn 12832: }
12833:
1.1138 raeburn 12834: # ---------------------------------------------------------- Read managers table
12835: {
12836: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12837: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12838: while (my $configline=<$config>) {
12839: chomp($configline);
12840: next if ($configline =~ /^\#/);
12841: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12842: $managerstab{$configline} = 1;
12843: }
12844: }
12845: close($config);
12846: }
12847: }
12848: }
12849:
1.329 matthew 12850: # ------------- set up temporary directory
12851: {
1.1117 foxr 12852: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12853:
1.11 www 12854: }
12855:
1.794 albertel 12856: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12857: 'compress_threshold'=> 20_000,
12858: });
1.185 www 12859:
1.281 www 12860: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12861: $dumpcount=0;
1.958 www 12862: $locknum=0;
1.22 www 12863:
1.163 harris41 12864: &logtouch();
1.672 albertel 12865: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12866: $readit=1;
1.564 albertel 12867: {
12868: use integer;
12869: my $test=(2**32)+1;
1.568 albertel 12870: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12871: &logthis(" Detected 64bit platform ($_64bit)");
12872: }
1.195 www 12873: }
1.1 albertel 12874: }
1.179 www 12875:
1.1 albertel 12876: 1;
1.191 harris41 12877: __END__
12878:
1.243 albertel 12879: =pod
12880:
1.191 harris41 12881: =head1 NAME
12882:
1.243 albertel 12883: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12884:
12885: =head1 SYNOPSIS
12886:
1.243 albertel 12887: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12888:
12889: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12890:
1.243 albertel 12891: Common parameters:
12892:
12893: =over 4
12894:
12895: =item *
12896:
12897: $uname : an internal username (if $cname expecting a course Id specifically)
12898:
12899: =item *
12900:
12901: $udom : a domain (if $cdom expecting a course's domain specifically)
12902:
12903: =item *
12904:
12905: $symb : a resource instance identifier
12906:
12907: =item *
12908:
12909: $namespace : the name of a .db file that contains the data needed or
12910: being set.
12911:
12912: =back
12913:
1.394 bowersj2 12914: =head1 OVERVIEW
1.191 harris41 12915:
1.394 bowersj2 12916: lonnet provides subroutines which interact with the
12917: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12918: about classes, users, and resources.
1.243 albertel 12919:
12920: For many of these objects you can also use this to store data about
12921: them or modify them in various ways.
1.191 harris41 12922:
1.394 bowersj2 12923: =head2 Symbs
1.191 harris41 12924:
1.394 bowersj2 12925: To identify a specific instance of a resource, LON-CAPA uses symbols
12926: or "symbs"X<symb>. These identifiers are built from the URL of the
12927: map, the resource number of the resource in the map, and the URL of
12928: the resource itself. The latter is somewhat redundant, but might help
12929: if maps change.
12930:
12931: An example is
12932:
12933: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12934:
12935: The respective map entry is
12936:
12937: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12938: title="Problem 2">
12939: </resource>
12940:
12941: Symbs are used by the random number generator, as well as to store and
12942: restore data specific to a certain instance of for example a problem.
12943:
12944: =head2 Storing And Retrieving Data
12945:
12946: X<store()>X<cstore()>X<restore()>Three of the most important functions
12947: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12948: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12949: is is the non-critical message twin of cstore. These functions are for
12950: handlers to store a perl hash to a user's permanent data space in an
12951: easy manner, and to retrieve it again on another call. It is expected
12952: that a handler would use this once at the beginning to retrieve data,
12953: and then again once at the end to send only the new data back.
12954:
12955: The data is stored in the user's data directory on the user's
12956: homeserver under the ID of the course.
12957:
12958: The hash that is returned by restore will have all of the previous
12959: value for all of the elements of the hash.
12960:
12961: Example:
12962:
12963: #creating a hash
12964: my %hash;
12965: $hash{'foo'}='bar';
12966:
12967: #storing it
12968: &Apache::lonnet::cstore(\%hash);
12969:
12970: #changing a value
12971: $hash{'foo'}='notbar';
12972:
12973: #adding a new value
12974: $hash{'bar'}='foo';
12975: &Apache::lonnet::cstore(\%hash);
12976:
12977: #retrieving the hash
12978: my %history=&Apache::lonnet::restore();
12979:
12980: #print the hash
12981: foreach my $key (sort(keys(%history))) {
12982: print("\%history{$key} = $history{$key}");
12983: }
12984:
12985: Will print out:
1.191 harris41 12986:
1.394 bowersj2 12987: %history{1:foo} = bar
12988: %history{1:keys} = foo:timestamp
12989: %history{1:timestamp} = 990455579
12990: %history{2:bar} = foo
12991: %history{2:foo} = notbar
12992: %history{2:keys} = foo:bar:timestamp
12993: %history{2:timestamp} = 990455580
12994: %history{bar} = foo
12995: %history{foo} = notbar
12996: %history{timestamp} = 990455580
12997: %history{version} = 2
12998:
12999: Note that the special hash entries C<keys>, C<version> and
13000: C<timestamp> were added to the hash. C<version> will be equal to the
13001: total number of versions of the data that have been stored. The
13002: C<timestamp> attribute will be the UNIX time the hash was
13003: stored. C<keys> is available in every historical section to list which
13004: keys were added or changed at a specific historical revision of a
13005: hash.
13006:
13007: B<Warning>: do not store the hash that restore returns directly. This
13008: will cause a mess since it will restore the historical keys as if the
13009: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13010:
1.394 bowersj2 13011: Calling convention:
1.191 harris41 13012:
1.1172.2.27 raeburn 13013: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 13014: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13015:
1.394 bowersj2 13016: For more detailed information, see lonnet specific documentation.
1.191 harris41 13017:
1.394 bowersj2 13018: =head1 RETURN MESSAGES
1.191 harris41 13019:
1.394 bowersj2 13020: =over 4
1.191 harris41 13021:
1.394 bowersj2 13022: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13023:
1.394 bowersj2 13024: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13025: when the connection is brought back up
1.191 harris41 13026:
1.394 bowersj2 13027: =item * B<con_failed>: unable to contact remote host and unable to save message
13028: for later delivery
1.191 harris41 13029:
1.967 bisitz 13030: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13031:
1.394 bowersj2 13032: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13033: that was requested
1.191 harris41 13034:
1.243 albertel 13035: =back
1.191 harris41 13036:
1.243 albertel 13037: =head1 PUBLIC SUBROUTINES
1.191 harris41 13038:
1.243 albertel 13039: =head2 Session Environment Functions
1.191 harris41 13040:
1.243 albertel 13041: =over 4
1.191 harris41 13042:
1.394 bowersj2 13043: =item *
13044: X<appenv()>
1.949 raeburn 13045: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13046: the user envirnoment file, and will be restored for each access this
1.620 albertel 13047: user makes during this session, also modifies the %env for the current
1.949 raeburn 13048: process. Optional rolesarrayref - if defined contains a reference to an array
13049: of roles which are exempt from the restriction on modifying user.role entries
13050: in the user's environment.db and in %env.
1.191 harris41 13051:
13052: =item *
1.394 bowersj2 13053: X<delenv()>
1.987 raeburn 13054: B<delenv($delthis,$regexp)>: removes all items from the session
13055: environment file that begin with $delthis. If the
13056: optional second arg - $regexp - is true, $delthis is treated as a
13057: regular expression, otherwise \Q$delthis\E is used.
13058: The values are also deleted from the current processes %env.
1.191 harris41 13059:
1.795 albertel 13060: =item * get_env_multiple($name)
13061:
13062: gets $name from the %env hash, it seemlessly handles the cases where multiple
13063: values may be defined and end up as an array ref.
13064:
13065: returns an array of values
13066:
1.243 albertel 13067: =back
13068:
13069: =head2 User Information
1.191 harris41 13070:
1.243 albertel 13071: =over 4
1.191 harris41 13072:
13073: =item *
1.394 bowersj2 13074: X<queryauthenticate()>
13075: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13076: authentication scheme
13077:
13078: =item *
1.394 bowersj2 13079: X<authenticate()>
1.1073 raeburn 13080: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13081: authenticate user from domain's lib servers (first use the current
13082: one). C<$upass> should be the users password.
1.1073 raeburn 13083: $checkdefauth is optional (value is 1 if a check should be made to
13084: authenticate user using default authentication method, and allow
13085: account creation if username does not have account in the domain).
13086: $clientcancheckhost is optional (value is 1 if checking whether the
13087: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13088:
13089: =item *
1.394 bowersj2 13090: X<homeserver()>
13091: B<homeserver($uname,$udom)>: find the server which has
13092: the user's directory and files (there must be only one), this caches
13093: the answer, and also caches if there is a borken connection.
1.191 harris41 13094:
13095: =item *
1.394 bowersj2 13096: X<idget()>
13097: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13098: (IDs are a unique resource in a domain, there must be only 1 ID per
13099: username, and only 1 username per ID in a specific domain) (returns
13100: hash: id=>name,id=>name)
1.191 harris41 13101:
13102: =item *
1.394 bowersj2 13103: X<idrget()>
13104: B<idrget($udom,@unames)>: find the IDs behind a list of
13105: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13106:
13107: =item *
1.394 bowersj2 13108: X<idput()>
13109: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 13110:
13111: =item *
1.394 bowersj2 13112: X<rolesinit()>
1.1169 droeschl 13113: B<rolesinit($udom,$username)>: get user privileges.
13114: returns user role, first access and timer interval hashes
1.243 albertel 13115:
13116: =item *
1.1171 droeschl 13117: X<privileged()>
13118: B<privileged($username,$domain)>: returns a true if user has a
13119: privileged and active role (i.e. su or dc), false otherwise.
13120:
13121: =item *
1.551 albertel 13122: X<getsection()>
13123: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13124: course $cname, return section name/number or '' for "not in course"
13125: and '-1' for "no section"
13126:
13127: =item *
1.394 bowersj2 13128: X<userenvironment()>
13129: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13130: passed in @what from the requested user's environment, returns a hash
13131:
1.858 raeburn 13132: =item *
13133: X<userlog_query()>
1.859 albertel 13134: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13135: activity.log file. %filters defines filters applied when parsing the
13136: log file. These can be start or end timestamps, or the type of action
13137: - log to look for Login or Logout events, check for Checkin or
13138: Checkout, role for role selection. The response is in the form
13139: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13140: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13141:
1.243 albertel 13142: =back
13143:
13144: =head2 User Roles
13145:
13146: =over 4
13147:
13148: =item *
13149:
1.1172.2.65 raeburn 13150: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13151: returns codes for allowed actions.
13152:
13153: The first argument is required, all others are optional.
13154:
13155: $priv is the privilege being checked.
13156: $uri contains additional information about what is being checked for access (e.g.,
13157: URL, course ID etc.).
13158: $symb is the unique resource instance identifier in a course; if needed,
13159: but not provided, it will be retrieved via a call to &symbread().
13160: $role is the role for which a priv is being checked (only used if priv is evb).
13161: $clientip is the user's IP address (only used when checking for access to portfolio
13162: files).
13163: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13164: prevents recursive calls to &allowed.
13165:
1.243 albertel 13166: F: full access
13167: U,I,K: authentication modes (cxx only)
13168: '': forbidden
13169: 1: user needs to choose course
13170: 2: browse allowed
1.766 albertel 13171: A: passphrase authentication needed
1.1172.2.65 raeburn 13172: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13173:
13174: =item *
13175:
1.1172.2.13 raeburn 13176: constructaccess($url,$setpriv) : check for access to construction space URL
13177:
13178: See if the owner domain and name in the URL match those in the
13179: expected environment. If so, return three element list
13180: ($ownername,$ownerdomain,$ownerhome).
13181:
13182: Otherwise return the null string.
13183:
13184: If second argument 'setpriv' is true, it assigns the privileges,
13185: and returns the same three element list, unless the owner has
13186: blocked "ad hoc" Domain Coordinator access to the Author Space,
13187: in which case the null string is returned.
13188:
13189: =item *
13190:
1.243 albertel 13191: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
13192: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
13193: and course level
13194:
13195: =item *
13196:
1.988 raeburn 13197: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13198: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13199: $type is Course (default) or Community.
1.988 raeburn 13200: If $forcedefault evaluates to true, text returned will be default
13201: text for $type. Otherwise, if this is a course, the text returned
13202: will be a custom name for the role (if defined in the course's
13203: environment). If no custom name is defined the default is returned.
13204:
1.832 raeburn 13205: =item *
13206:
1.1172.2.23 raeburn 13207: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13208: All arguments are optional. Returns a hash of a roles, either for
13209: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13210: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13211: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13212: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13213: For each key, value is set to colon-separated start and end times for
13214: the role. If no username and domain are specified, will default to
1.934 raeburn 13215: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13216: of role statuses (active, future or previous), roles
13217: (e.g., cc,in, st etc.) and domains of the roles which can be used
13218: to restrict the list of roles reported. If no array ref is
13219: provided for types, will default to return only active roles.
1.834 albertel 13220:
1.1172.2.13 raeburn 13221: =item *
13222:
13223: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
13224: user: $uname:$udom has a role in the course: $cdom_$cnum.
13225:
13226: Additional optional arguments are: $type (if role checking is to be restricted
13227: to certain user status types -- previous (expired roles), active (currently
13228: available roles) or future (roles available in the future), and
13229: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 13230: have active Domain Coordinator role in course's domain or in additional
13231: domains (specified in 'Domains to check for privileged users' in course
13232: environment -- set via: Course Settings -> Classlists and staff listing).
13233:
13234: =item *
13235:
13236: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13237: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13238: $possdomains and $possroles are optional array refs -- to domains to check and
13239: roles to check. If $possdomains is not specified, a dump will be done of the
13240: users' roles.db to check for a dc or su role in any domain. This can be
13241: time consuming if &privileged is called repeatedly (e.g., when displaying a
13242: classlist), so in such cases, supplying a $possdomains array is preferred, as
13243: this then allows &privileged_by_domain() to be used, which caches the identity
13244: of privileged users, eliminating the need for repeated calls to &dump().
13245:
13246: =item *
13247:
13248: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13249: where the outer hash keys are domains specified in the $possdomains array ref,
13250: next inner hash keys are privileged roles specified in the $roles array ref,
13251: and the innermost hash contains key = value pairs for username:domain = end:start
13252: for active or future "privileged" users with that role in that domain. To avoid
13253: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13254: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 13255:
1.243 albertel 13256: =back
13257:
13258: =head2 User Modification
13259:
13260: =over 4
13261:
13262: =item *
13263:
1.957 raeburn 13264: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13265: user for the level given by URL. Optional start and end dates (leave empty
13266: string or zero for "no date")
1.191 harris41 13267:
13268: =item *
13269:
1.243 albertel 13270: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13271: change a users, password, possible return values are: ok,
13272: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13273: refused
1.191 harris41 13274:
13275: =item *
13276:
1.243 albertel 13277: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13278:
13279: =item *
13280:
1.1058 raeburn 13281: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13282: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13283:
13284: will update user information (firstname,middlename,lastname,generation,
13285: permanentemail), and if forceid is true, student/employee ID also.
13286: A user's institutional affiliation(s) can also be updated.
13287: User information fields will not be overwritten with empty entries
13288: unless the field is included in the $candelete array reference.
13289: This array is included when a single user is modified via "Manage Users",
13290: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13291:
13292: =item *
13293:
1.286 matthew 13294: modifystudent
13295:
1.957 raeburn 13296: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 13297: The course id is resolved based on the current user's environment.
13298: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13299: associated with a course.
13300:
1.297 matthew 13301: This call is essentially a wrapper for lonnet::modifyuser and
13302: lonnet::modify_student_enrollment
1.286 matthew 13303:
13304: Inputs:
13305:
13306: =over 4
13307:
1.957 raeburn 13308: =item B<$udom> Student's loncapa domain
1.286 matthew 13309:
1.957 raeburn 13310: =item B<$uname> Student's loncapa login name
1.286 matthew 13311:
1.964 bisitz 13312: =item B<$uid> Student/Employee ID
1.286 matthew 13313:
1.957 raeburn 13314: =item B<$umode> Student's authentication mode
1.286 matthew 13315:
1.957 raeburn 13316: =item B<$upass> Student's password
1.286 matthew 13317:
1.957 raeburn 13318: =item B<$first> Student's first name
1.286 matthew 13319:
1.957 raeburn 13320: =item B<$middle> Student's middle name
1.286 matthew 13321:
1.957 raeburn 13322: =item B<$last> Student's last name
1.286 matthew 13323:
1.957 raeburn 13324: =item B<$gene> Student's generation
1.286 matthew 13325:
1.957 raeburn 13326: =item B<$usec> Student's section in course
1.286 matthew 13327:
13328: =item B<$end> Unix time of the roles expiration
13329:
13330: =item B<$start> Unix time of the roles start date
13331:
13332: =item B<$forceid> If defined, allow $uid to be changed
13333:
13334: =item B<$desiredhome> server to use as home server for student
13335:
1.957 raeburn 13336: =item B<$email> Student's permanent e-mail address
13337:
13338: =item B<$type> Type of enrollment (auto or manual)
13339:
1.963 raeburn 13340: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13341:
13342: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13343:
1.963 raeburn 13344: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13345:
1.963 raeburn 13346: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13347:
1.1172.2.19 raeburn 13348: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13349:
13350: =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 13351:
1.286 matthew 13352: =back
1.297 matthew 13353:
13354: =item *
13355:
13356: modify_student_enrollment
13357:
1.1172.2.31 raeburn 13358: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13359: 'role.request.course' must be defined for this function to proceed.
13360:
13361: Inputs:
13362:
13363: =over 4
13364:
1.1172.2.31 raeburn 13365: =item $udom, student's domain
1.297 matthew 13366:
1.1172.2.31 raeburn 13367: =item $uname, student's name
1.297 matthew 13368:
1.1172.2.31 raeburn 13369: =item $uid, student's user id
1.297 matthew 13370:
1.1172.2.31 raeburn 13371: =item $first, student's first name
1.297 matthew 13372:
13373: =item $middle
13374:
13375: =item $last
13376:
13377: =item $gene
13378:
13379: =item $usec
13380:
13381: =item $end
13382:
13383: =item $start
13384:
1.957 raeburn 13385: =item $type
13386:
13387: =item $locktype
13388:
13389: =item $cid
13390:
13391: =item $selfenroll
13392:
13393: =item $context
13394:
1.1172.2.19 raeburn 13395: =item $credits, number of credits student will earn from this class
13396:
1.1172.2.76 raeburn 13397: =item $instsec, institutional course section code for student
13398:
1.297 matthew 13399: =back
13400:
1.191 harris41 13401:
13402: =item *
13403:
1.243 albertel 13404: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13405: custom role; give a custom role to a user for the level given by URL. Specify
13406: name and domain of role author, and role name
1.191 harris41 13407:
13408: =item *
13409:
1.243 albertel 13410: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13411:
13412: =item *
13413:
1.243 albertel 13414: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13415:
13416: =back
13417:
13418: =head2 Course Infomation
13419:
13420: =over 4
1.191 harris41 13421:
13422: =item *
13423:
1.1118 foxr 13424: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13425: specified course id, including all environment settings for the
13426: course, the description of the course will be in the hash under the
13427: key 'description'
1.191 harris41 13428:
1.1118 foxr 13429: $options is an optional parameter that if supplied is a hash reference that controls
13430: what how this function works. It has the following key/values:
13431:
13432: =over 4
13433:
13434: =item freshen_cache
13435:
13436: If defined, and the environment cache for the course is valid, it is
13437: returned in the returned hash.
13438:
13439: =item one_time
13440:
13441: If defined, the last cache time is set to _now_
13442:
13443: =item user
13444:
13445: If defined, the supplied username is used instead of the current user.
13446:
13447:
13448: =back
13449:
1.191 harris41 13450: =item *
13451:
1.624 albertel 13452: resdata($name,$domain,$type,@which) : request for current parameter
13453: setting for a specific $type, where $type is either 'course' or 'user',
13454: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 13455: answers for 10 minutes.
1.243 albertel 13456:
1.877 foxr 13457: =item *
13458:
13459: get_courseresdata($courseid, $domain) : dump the entire course resource
13460: data base, returning a hash that is keyed by the resource name and has
13461: values that are the resource value. I believe that the timestamps and
13462: versions are also returned.
13463:
1.1172.2.31 raeburn 13464: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13465: supplemental content area. This routine caches the number of files for
13466: 10 minutes.
13467:
1.243 albertel 13468: =back
13469:
13470: =head2 Course Modification
13471:
13472: =over 4
1.191 harris41 13473:
13474: =item *
13475:
1.243 albertel 13476: writecoursepref($courseid,%prefs) : write preferences (environment
13477: database) for a course
1.191 harris41 13478:
13479: =item *
13480:
1.1011 raeburn 13481: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13482:
13483: =item *
13484:
1.1038 raeburn 13485: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13486:
1.1167 droeschl 13487: =item *
13488:
13489: is_course($courseid), is_course($cdom, $cnum)
13490:
13491: Accepts either a combined $courseid (in the form of domain_courseid) or the
13492: two component version $cdom, $cnum. It checks if the specified course exists.
13493:
13494: Returns:
13495: undef if the course doesn't exist, otherwise
13496: in scalar context the combined courseid.
13497: in list context the two components of the course identifier, domain and
13498: courseid.
13499:
1.243 albertel 13500: =back
13501:
13502: =head2 Resource Subroutines
13503:
13504: =over 4
1.191 harris41 13505:
13506: =item *
13507:
1.243 albertel 13508: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13509:
13510: =item *
13511:
1.243 albertel 13512: repcopy($filename) : subscribes to the requested file, and attempts to
13513: replicate from the owning library server, Might return
1.607 raeburn 13514: 'unavailable', 'not_found', 'forbidden', 'ok', or
13515: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13516: resource. Expects the local filesystem pathname
13517: (/home/httpd/html/res/....)
13518:
13519: =back
13520:
13521: =head2 Resource Information
13522:
13523: =over 4
1.191 harris41 13524:
13525: =item *
13526:
1.1172.2.28 raeburn 13527: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13528: and returns the value of a variety of different possible values,
13529: $varname should be a request string, and the other parameters can be
13530: used to specify who and what one is asking about. Ordinarily, $cid
13531: does not need to be specified, as it is retrived from
13532: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13533: within lonuserstate::loadmap() when initializing a course, before
13534: $env{'request.course.id'} has been set, so it needs to be provided
13535: in that one case.
1.243 albertel 13536:
13537: Possible values for $varname are environment.lastname (or other item
13538: from the envirnment hash), user.name (or someother aspect about the
13539: user), resource.0.maxtries (or some other part and parameter of a
13540: resource)
1.204 albertel 13541:
13542: =item *
13543:
1.243 albertel 13544: directcondval($number) : get current value of a condition; reads from a state
13545: string
1.204 albertel 13546:
13547: =item *
13548:
1.243 albertel 13549: condval($condidx) : value of condition index based on state
1.204 albertel 13550:
13551: =item *
13552:
1.243 albertel 13553: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13554: resource's metadata, $what should be either a specific key, or either
13555: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13556: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13557:
13558: this function automatically caches all requests
1.191 harris41 13559:
13560: =item *
13561:
1.243 albertel 13562: metadata_query($query,$custom,$customshow) : make a metadata query against the
13563: network of library servers; returns file handle of where SQL and regex results
13564: will be stored for query
1.191 harris41 13565:
13566: =item *
13567:
1.1172.2.66 raeburn 13568: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
13569: return symbolic list entry (all arguments optional).
13570:
13571: Args: filename is the filename (including path) for the file for which a symb
13572: is required; donotrecurse, if true will prevent calls to allowed() being made
13573: to check access status if more than one resource was found in the bighash
13574: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
13575: a randompick); ignorecachednull, if true will prevent a symb of '' being
13576: returned if $env{$cache_str} is defined as ''; checkforblock if true will
13577: cause possible symbs to be checked to determine if they are subject to content
13578: blocking, if so they will not be included as possible symbs; possibles is a
13579: ref to a hash, which, as a side effect, will be populated with all possible
13580: symbs (content blocking not tested).
13581:
1.243 albertel 13582: returns the data handle
1.191 harris41 13583:
13584: =item *
13585:
1.1172.2.17 raeburn 13586: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 13587: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13588: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 13589: on failure, user must be in a course, as it assumes the existence of
13590: the course initial hash, and uses $env('request.course.id'}. The third
13591: arg is an optional reference to a scalar. If this arg is passed in the
13592: call to symbverify, it will be set to 1 if the symb has been set to be
13593: encrypted; otherwise it will be null.
1.243 albertel 13594:
1.191 harris41 13595: =item *
13596:
1.243 albertel 13597: symbclean($symb) : removes versions numbers from a symb, returns the
13598: cleaned symb
1.191 harris41 13599:
13600: =item *
13601:
1.243 albertel 13602: is_on_map($uri) : checks if the $uri is somewhere on the current
13603: course map, user must be in a course for it to work.
1.191 harris41 13604:
13605: =item *
13606:
1.243 albertel 13607: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13608:
13609: =item *
13610:
1.243 albertel 13611: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13612: a random seed, all arguments are optional, if they aren't sent it uses the
13613: environment to derive them. Note: if symb isn't sent and it can't get one
13614: from &symbread it will use the current time as its return value
1.191 harris41 13615:
13616: =item *
13617:
1.243 albertel 13618: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13619: unfakeable, receipt
1.191 harris41 13620:
13621: =item *
13622:
1.620 albertel 13623: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13624:
13625: =item *
13626:
1.243 albertel 13627: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13628:
13629: =item *
13630:
1.243 albertel 13631: 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 13632:
13633: =item *
13634:
1.243 albertel 13635: 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 13636:
13637: =item *
13638:
1.243 albertel 13639: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13640:
13641: =item *
13642:
1.243 albertel 13643: devalidate($symb) : devalidate temporary spreadsheet calculations,
13644: forcing spreadsheet to reevaluate the resource scores next time.
13645:
1.1172.2.13 raeburn 13646: =item *
13647:
13648: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13649: when viewing in course context.
13650:
13651: input: six args -- filename (decluttered), course number, course domain,
13652: url, symb (if registered) and group (if this is a
13653: group item -- e.g., bulletin board, group page etc.).
13654:
13655: output: array of five scalars --
13656: $cfile -- url for file editing if editable on current server
13657: $home -- homeserver of resource (i.e., for author if published,
13658: or course if uploaded.).
13659: $switchserver -- 1 if server switch will be needed.
13660: $forceedit -- 1 if icon/link should be to go to edit mode
13661: $forceview -- 1 if icon/link should be to go to view mode
13662:
13663: =item *
13664:
13665: is_course_upload($file,$cnum,$cdom)
13666:
13667: Used in course context to determine if current file was uploaded to
13668: the course (i.e., would be found in /userfiles/docs on the course's
13669: homeserver.
13670:
13671: input: 3 args -- filename (decluttered), course number and course domain.
13672: output: boolean -- 1 if file was uploaded.
13673:
1.243 albertel 13674: =back
13675:
13676: =head2 Storing/Retreiving Data
13677:
13678: =over 4
1.191 harris41 13679:
13680: =item *
13681:
1.1172.2.64 raeburn 13682: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13683: permanently for this url; hashref needs to be given and should be a \%hashname;
13684: the remaining args aren't required and if they aren't passed or are '' they will
13685: be derived from the env (with the exception of $laststore, which is an
13686: optional arg used when a user's submission is stored in grading).
13687: $laststore is $version=$timestamp, where $version is the most recent version
13688: number retrieved for the corresponding $symb in the $namespace db file, and
13689: $timestamp is the timestamp for that transaction (UNIX time).
13690: $laststore is currently only passed when cstore() is called by
13691: structuretags::finalize_storage().
1.191 harris41 13692:
13693: =item *
13694:
1.1172.2.64 raeburn 13695: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13696: but uses critical subroutine
1.191 harris41 13697:
13698: =item *
13699:
1.243 albertel 13700: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13701: all args are optional
1.191 harris41 13702:
13703: =item *
13704:
1.717 albertel 13705: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13706: dumps the complete (or key matching regexp) namespace into a hash
13707: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13708: normally &store()ed into
13709:
13710: $range should be either an integer '100' (give me the first 100
13711: matching records)
13712: or be two integers sperated by a - with no spaces
13713: '30-50' (give me the 30th through the 50th matching
13714: records)
13715:
13716:
13717: =item *
13718:
1.1172.2.59 raeburn 13719: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 13720: replaces a &store() version of data with a replacement set of data
13721: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 13722: reference. If $tolog is true, the transaction is logged in the courselog
13723: with an action=PUTSTORE.
1.717 albertel 13724:
13725: =item *
13726:
1.243 albertel 13727: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13728: works very similar to store/cstore, but all data is stored in a
13729: temporary location and can be reset using tmpreset, $storehash should
13730: be a hash reference, returns nothing on success
1.191 harris41 13731:
13732: =item *
13733:
1.243 albertel 13734: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13735: similar to restore, but all data is stored in a temporary location and
13736: can be reset using tmpreset. Returns a hash of values on success,
13737: error string otherwise.
1.191 harris41 13738:
13739: =item *
13740:
1.243 albertel 13741: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13742: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13743:
13744: =item *
13745:
1.243 albertel 13746: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13747: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13748:
13749: =item *
13750:
1.243 albertel 13751: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13752: namesp ($udom and $uname are optional)
1.191 harris41 13753:
13754: =item *
13755:
1.702 albertel 13756: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13757: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13758: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13759:
1.702 albertel 13760: $range should be either an integer '100' (give me the first 100
13761: matching records)
13762: or be two integers sperated by a - with no spaces
13763: '30-50' (give me the 30th through the 50th matching
13764: records)
1.449 matthew 13765: =item *
13766:
13767: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13768: $store can be a scalar, an array reference, or if the amount to be
13769: incremented is > 1, a hash reference.
13770:
13771: ($udom and $uname are optional)
1.191 harris41 13772:
13773: =item *
13774:
1.243 albertel 13775: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13776: ($udom and $uname are optional)
1.191 harris41 13777:
13778: =item *
13779:
1.243 albertel 13780: cput($namespace,$storehash,$udom,$uname) : critical put
13781: ($udom and $uname are optional)
1.191 harris41 13782:
13783: =item *
13784:
1.748 albertel 13785: newput($namespace,$storehash,$udom,$uname) :
13786:
13787: Attempts to store the items in the $storehash, but only if they don't
13788: currently exist, if this succeeds you can be certain that you have
13789: successfully created a new key value pair in the $namespace db.
13790:
13791:
13792: Args:
13793: $namespace: name of database to store values to
13794: $storehash: hashref to store to the db
13795: $udom: (optional) domain of user containing the db
13796: $uname: (optional) name of user caontaining the db
13797:
13798: Returns:
13799: 'ok' -> succeeded in storing all keys of $storehash
13800: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13801: least <key> already existed in the db (other
13802: requested keys may also already exist)
1.967 bisitz 13803: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13804: 'con_lost' -> unable to contact request server
13805: 'refused' -> action was not allowed by remote machine
13806:
13807:
13808: =item *
13809:
1.243 albertel 13810: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13811: reference filled in from namesp (encrypts the return communication)
13812: ($udom and $uname are optional)
1.191 harris41 13813:
13814: =item *
13815:
1.243 albertel 13816: log($udom,$name,$home,$message) : write to permanent log for user; use
13817: critical subroutine
13818:
1.806 raeburn 13819: =item *
13820:
1.860 raeburn 13821: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13822: array reference filled in from namespace found in domain level on either
13823: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13824:
13825: =item *
13826:
1.860 raeburn 13827: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13828: domain level either on specified domain server ($uhome) or primary domain
13829: server ($udom and $uhome are optional)
1.806 raeburn 13830:
1.943 raeburn 13831: =item *
13832:
1.1172.2.35 raeburn 13833: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13834: for: authentication, language, quotas, timezone, date locale, and portal URL in
13835: the target domain.
13836:
13837: May also include additional key => value pairs for the following groups:
13838:
13839: =over
13840:
13841: =item
13842: disk quotas (MB allocated by default to portfolios and authoring spaces).
13843:
13844: =over
13845:
13846: =item defaultquota, authorquota
13847:
13848: =back
13849:
13850: =item
13851: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13852: portfolio for users).
13853:
13854: =over
13855:
13856: =item
13857: aboutme, blog, webdav, portfolio
13858:
13859: =back
13860:
13861: =item
13862: requestcourses: ability to request courses, and how requests are processed.
13863:
13864: =over
13865:
13866: =item
1.1172.2.37 raeburn 13867: official, unofficial, community, textbook
1.1172.2.35 raeburn 13868:
13869: =back
13870:
13871: =item
13872: inststatus: types of institutional affiliation, and order in which they are displayed.
13873:
13874: =over
13875:
13876: =item
1.1172.2.44 raeburn 13877: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 13878:
13879: =back
13880:
13881: =item
13882: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13883: for course's uploaded content.
13884:
13885: =over
13886:
13887: =item
1.1172.2.68 raeburn 13888: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13889: communityquota, textbookquota
1.1172.2.35 raeburn 13890:
13891: =back
13892:
13893: =item
13894: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13895: on your servers.
13896:
13897: =over
13898:
13899: =item
13900: remotesessions, hostedsessions
13901:
13902: =back
13903:
13904: =back
13905:
13906: In cases where a domain coordinator has never used the "Set Domain Configuration"
13907: utility to create a configuration.db file on a domain's primary library server
13908: only the following domain defaults: auth_def, auth_arg_def, lang_def
13909: -- corresponding values are authentication type (internal, krb4, krb5,
13910: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13911: will be available. Values are retrieved from cache (if current), unless the
13912: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13913: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13914:
13915: Typical usage:
1.943 raeburn 13916:
1.1172.2.35 raeburn 13917: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13918:
1.243 albertel 13919: =back
13920:
13921: =head2 Network Status Functions
13922:
13923: =over 4
1.191 harris41 13924:
13925: =item *
13926:
1.1137 raeburn 13927: dirlist() : return directory list based on URI (first arg).
13928:
13929: Inputs: 1 required, 5 optional.
13930:
13931: =over
13932:
13933: =item
13934: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13935:
13936: =item
13937: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13938:
13939: =item
13940: $username - username of user/course to be listed. Extracted from $uri if absent.
13941:
13942: =item
13943: $getpropath - boolean: 1 if prepend path using &propath().
13944:
13945: =item
13946: $getuserdir - boolean: 1 if prepend path for "userfiles".
13947:
13948: =item
13949: $alternateRoot - path to prepend in place of path from $uri.
13950:
13951: =back
13952:
13953: Returns: Array of up to two items.
13954:
13955: =over
13956:
13957: a reference to an array of files/subdirectories
13958:
13959: =over
13960:
13961: Each element in the array of files/subdirectories is a & separated list of
13962: item name and the result of running stat on the item. If dirlist was requested
13963: for a file instead of a directory, the item name will be ''. For a directory
13964: listing, if the item is a metadata file, the element will end &N&M
13965: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13966: default copyright set (1).
13967:
13968: =back
13969:
13970: a scalar containing error condition (if encountered).
13971:
13972: =over
13973:
13974: =item
13975: no_host (no homeserver identified for $username:$domain).
13976:
13977: =item
13978: no_such_host (server contacted for listing not identified as valid host).
13979:
13980: =item
13981: con_lost (connection to remote server failed).
13982:
13983: =item
13984: refused (invalid $username:$domain received on lond side).
13985:
13986: =item
13987: no_such_dir (directory at specified path on lond side does not exist).
13988:
13989: =item
13990: empty (directory at specified path on lond side is empty).
13991:
13992: =over
13993:
13994: This is currently not encountered because the &ls3, &ls2,
13995: &ls (_handler) routines on the lond side do not filter out
13996: . and .. from a directory listing.
13997:
13998: =back
13999:
14000: =back
14001:
14002: =back
1.191 harris41 14003:
14004: =item *
14005:
1.243 albertel 14006: spareserver() : find server with least workload from spare.tab
14007:
1.986 foxr 14008:
14009: =item *
14010:
14011: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14012: if there is no corresponding loncapa host.
14013:
1.243 albertel 14014: =back
14015:
1.986 foxr 14016:
1.243 albertel 14017: =head2 Apache Request
14018:
14019: =over 4
1.191 harris41 14020:
14021: =item *
14022:
1.243 albertel 14023: ssi($url,%hash) : server side include, does a complete request cycle on url to
14024: localhost, posts hash
14025:
14026: =back
14027:
14028: =head2 Data to String to Data
14029:
14030: =over 4
1.191 harris41 14031:
14032: =item *
14033:
1.243 albertel 14034: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14035: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14036:
14037: =item *
14038:
1.243 albertel 14039: hashref2str($hashref) : convert a hashref into a string complete with
14040: escaping and '=' and '&' separators, supports elements that are
14041: arrayrefs and hashrefs
1.191 harris41 14042:
14043: =item *
14044:
1.243 albertel 14045: arrayref2str($arrayref) : convert an arrayref into a string complete
14046: with escaping and '&' separators, supports elements that are arrayrefs
14047: and hashrefs
1.191 harris41 14048:
14049: =item *
14050:
1.243 albertel 14051: str2hash($string) : convert string to hash using unescaping and
14052: splitting on '=' and '&', supports elements that are arrayrefs and
14053: hashrefs
1.191 harris41 14054:
14055: =item *
14056:
1.243 albertel 14057: str2array($string) : convert string to hash using unescaping and
14058: splitting on '&', supports elements that are arrayrefs and hashrefs
14059:
14060: =back
14061:
14062: =head2 Logging Routines
14063:
14064:
14065: These routines allow one to make log messages in the lonnet.log and
14066: lonnet.perm logfiles.
1.191 harris41 14067:
1.1119 foxr 14068: =over 4
14069:
1.191 harris41 14070: =item *
14071:
1.243 albertel 14072: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14073:
14074: =item *
14075:
1.243 albertel 14076: logthis() : append message to the normal lonnet.log file, it gets
14077: preiodically rolled over and deleted.
1.191 harris41 14078:
14079: =item *
14080:
1.243 albertel 14081: logperm() : append a permanent message to lonnet.perm.log, this log
14082: file never gets deleted by any automated portion of the system, only
14083: messages of critical importance should go in here.
14084:
1.1119 foxr 14085:
1.243 albertel 14086: =back
14087:
14088: =head2 General File Helper Routines
14089:
14090: =over 4
1.191 harris41 14091:
14092: =item *
14093:
1.481 raeburn 14094: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14095: (a) files in /uploaded
14096: (i) If a local copy of the file exists -
14097: compares modification date of local copy with last-modified date for
14098: definitive version stored on home server for course. If local copy is
14099: stale, requests a new version from the home server and stores it.
14100: If the original has been removed from the home server, then local copy
14101: is unlinked.
14102: (ii) If local copy does not exist -
14103: requests the file from the home server and stores it.
14104:
14105: If $caller is 'uploadrep':
14106: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14107: for request for files originally uploaded via DOCS.
14108: - returns 'ok' if fresh local copy now available, -1 otherwise.
14109:
14110: Otherwise:
14111: This indicates a call from the content generation phase of the request.
14112: - returns the entire contents of the file or -1.
14113:
14114: (b) files in /res
14115: - returns the entire contents of a file or -1;
14116: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14117:
1.712 albertel 14118:
14119: =item *
14120:
14121: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14122: reference
14123:
14124: returns either a stat() list of data about the file or an empty list
14125: if the file doesn't exist or couldn't find out about it (connection
14126: problems or user unknown)
14127:
1.191 harris41 14128: =item *
14129:
1.243 albertel 14130: filelocation($dir,$file) : returns file system location of a file
14131: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14132: directory that relative $file lookups are to looked in ($dir of /a/dir
14133: and a file of ../bob will become /a/bob)
1.191 harris41 14134:
14135: =item *
14136:
14137: hreflocation($dir,$file) : returns file system location or a URL; same as
14138: filelocation except for hrefs
14139:
14140: =item *
14141:
1.1172.2.49 raeburn 14142: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14143: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14144:
1.243 albertel 14145: =back
14146:
1.608 albertel 14147: =head2 Usererfile file routines (/uploaded*)
14148:
14149: =over 4
14150:
14151: =item *
14152:
14153: userfileupload(): main rotine for putting a file in a user or course's
14154: filespace, arguments are,
14155:
1.620 albertel 14156: formname - required - this is the name of the element in $env where the
1.608 albertel 14157: filename, and the contents of the file to create/modifed exist
1.620 albertel 14158: the filename is in $env{'form.'.$formname.'.filename'} and the
14159: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14160: context - if coursedoc, store the file in the course of the active role
14161: of the current user;
14162: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14163: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14164: subdir - required - subdirectory to put the file in under ../userfiles/
14165: if undefined, it will be placed in "unknown"
14166:
14167: (This routine calls clean_filename() to remove any dangerous
14168: characters from the filename, and then calls finuserfileupload() to
14169: complete the transaction)
14170:
14171: returns either the url of the uploaded file (/uploaded/....) if successful
14172: and /adm/notfound.html if unsuccessful
14173:
14174: =item *
14175:
14176: clean_filename(): routine for cleaing a filename up for storage in
14177: userfile space, argument is:
14178:
14179: filename - proposed filename
14180:
14181: returns: the new clean filename
14182:
14183: =item *
14184:
1.1090 raeburn 14185: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14186: userspace, probably shouldn't be called directly
14187:
14188: docuname: username or courseid of destination for the file
14189: docudom: domain of user/course of destination for the file
14190: formname: same as for userfileupload()
1.1090 raeburn 14191: fname: filename (including subdirectories) for the file
14192: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14193: allfiles: reference to hash used to store objects found by parser
14194: codebase: reference to hash used for codebases of java objects found by parser
14195: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14196: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14197: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14198: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14199: context: if 'overwrite', will move the uploaded file from its temporary location to
14200: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14201: mimetype: reference to scalar to accommodate mime type determined
14202: from File::MMagic if $parser = parse.
1.608 albertel 14203:
14204: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14205: and /adm/notfound.html if unsuccessful (or an error message if context
14206: was 'overwrite').
14207:
1.608 albertel 14208:
14209: =item *
14210:
14211: renameuserfile(): renames an existing userfile to a new name
14212:
14213: Args:
14214: docuname: username or courseid of destination for the file
14215: docudom: domain of user/course of destination for the file
14216: old: current file name (including any subdirs under userfiles)
14217: new: desired file name (including any subdirs under userfiles)
14218:
14219: =item *
14220:
14221: mkdiruserfile(): creates a directory is a userfiles dir
14222:
14223: Args:
14224: docuname: username or courseid of destination for the file
14225: docudom: domain of user/course of destination for the file
14226: dir: dir to create (including any subdirs under userfiles)
14227:
14228: =item *
14229:
14230: removeuserfile(): removes a file that exists in userfiles
14231:
14232: Args:
14233: docuname: username or courseid of destination for the file
14234: docudom: domain of user/course of destination for the file
14235: fname: filname to delete (including any subdirs under userfiles)
14236:
14237: =item *
14238:
14239: removeuploadedurl(): convience function for removeuserfile()
14240:
14241: Args:
14242: url: a full /uploaded/... url to delete
14243:
1.747 albertel 14244: =item *
14245:
14246: get_portfile_permissions():
14247: Args:
14248: domain: domain of user or course contain the portfolio files
14249: user: name of user or num of course contain the portfolio files
14250: Returns:
14251: hashref of a dump of the proper file_permissions.db
14252:
14253:
14254: =item *
14255:
14256: get_access_controls():
14257:
14258: Args:
14259: current_permissions: the hash ref returned from get_portfile_permissions()
14260: group: (optional) the group you want the files associated with
14261: file: (optional) the file you want access info on
14262:
14263: Returns:
1.749 raeburn 14264: a hash (keys are file names) of hashes containing
14265: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14266: values are XML containing access control settings (see below)
1.747 albertel 14267:
14268: Internal notes:
14269:
1.749 raeburn 14270: access controls are stored in file_permissions.db as key=value pairs.
14271: key -> path to file/file_name\0uniqueID:scope_end_start
14272: where scope -> public,guest,course,group,domains or users.
14273: end -> UNIX time for end of access (0 -> no end date)
14274: start -> UNIX time for start of access
14275:
14276: value -> XML description of access control
14277: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14278: <start></start>
14279: <end></end>
14280:
14281: <password></password> for scope type = guest
14282:
14283: <domain></domain> for scope type = course or group
14284: <number></number>
14285: <roles id="">
14286: <role></role>
14287: <access></access>
14288: <section></section>
14289: <group></group>
14290: </roles>
14291:
14292: <dom></dom> for scope type = domains
14293:
14294: <users> for scope type = users
14295: <user>
14296: <uname></uname>
14297: <udom></udom>
14298: </user>
14299: </users>
14300: </scope>
14301:
14302: Access data is also aggregated for each file in an additional key=value pair:
14303: key -> path to file/file_name\0accesscontrol
14304: value -> reference to hash
14305: hash contains key = value pairs
14306: where key = uniqueID:scope_end_start
14307: value = UNIX time record was last updated
14308:
14309: Used to improve speed of look-ups of access controls for each file.
14310:
14311: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14312:
1.1172.2.13 raeburn 14313: =item *
14314:
1.749 raeburn 14315: modify_access_controls():
14316:
14317: Modifies access controls for a portfolio file
14318: Args
14319: 1. file name
14320: 2. reference to hash of required changes,
14321: 3. domain
14322: 4. username
14323: where domain,username are the domain of the portfolio owner
14324: (either a user or a course)
14325:
14326: Returns:
14327: 1. result of additions or updates ('ok' or 'error', with error message).
14328: 2. result of deletions ('ok' or 'error', with error message).
14329: 3. reference to hash of any new or updated access controls.
14330: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14331: key = integer (inbound ID)
1.1172.2.13 raeburn 14332: value = uniqueID
14333:
14334: =item *
14335:
14336: get_timebased_id():
14337:
14338: Attempts to get a unique timestamp-based suffix for use with items added to a
14339: course via the Course Editor (e.g., folders, composite pages,
14340: group bulletin boards).
14341:
14342: Args: (first three required; six others optional)
14343:
14344: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14345: docssequence, or name of group
14346:
14347: 2. keyid (alphanumeric): name of temporary locking key in hash,
14348: e.g., num, boardids
14349:
14350: 3. namespace: name of gdbm file used to store suffixes already assigned;
14351: file will be named nohist_namespace.db
14352:
14353: 4. cdom: domain of course; default is current course domain from %env
14354:
14355: 5. cnum: course number; default is current course number from %env
14356:
14357: 6. idtype: set to concat if an additional digit is to be appended to the
14358: unix timestamp to form the suffix, if the plain timestamp is already
14359: in use. Default is to not do this, but simply increment the unix
14360: timestamp by 1 until a unique key is obtained.
14361:
14362: 7. who: holder of locking key; defaults to user:domain for user.
14363:
14364: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14365: retrying); default is 3.
14366:
14367: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14368:
14369: Returns:
14370:
14371: 1. suffix obtained (numeric)
14372:
14373: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14374:
14375: 3. error: contains (localized) error message if an error occurred.
14376:
1.747 albertel 14377:
1.608 albertel 14378: =back
14379:
1.243 albertel 14380: =head2 HTTP Helper Routines
14381:
14382: =over 4
14383:
1.191 harris41 14384: =item *
14385:
14386: escape() : unpack non-word characters into CGI-compatible hex codes
14387:
14388: =item *
14389:
14390: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14391:
1.243 albertel 14392: =back
14393:
14394: =head1 PRIVATE SUBROUTINES
14395:
14396: =head2 Underlying communication routines (Shouldn't call)
14397:
14398: =over 4
14399:
14400: =item *
14401:
14402: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14403:
14404: =item *
14405:
14406: reply() : uses subreply to send a message to remote machine, logs all failures
14407:
14408: =item *
14409:
14410: critical() : passes a critical message to another server; if cannot
14411: get through then place message in connection buffer directory and
14412: returns con_delayed, if incapable of saving message, returns
14413: con_failed
14414:
14415: =item *
14416:
14417: reconlonc() : tries to reconnect lonc client processes.
14418:
14419: =back
14420:
14421: =head2 Resource Access Logging
14422:
14423: =over 4
14424:
14425: =item *
14426:
14427: flushcourselogs() : flush (save) buffer logs and access logs
14428:
14429: =item *
14430:
14431: courselog($what) : save message for course in hash
14432:
14433: =item *
14434:
14435: courseacclog($what) : save message for course using &courselog(). Perform
14436: special processing for specific resource types (problems, exams, quizzes, etc).
14437:
1.191 harris41 14438: =item *
14439:
14440: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14441: as a PerlChildExitHandler
1.243 albertel 14442:
14443: =back
14444:
14445: =head2 Other
14446:
14447: =over 4
14448:
14449: =item *
14450:
14451: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14452:
14453: =back
14454:
14455: =cut
1.877 foxr 14456:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>