Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.73
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.73! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.72 2016/08/05 15:34:27 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);
1286:
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.1129 raeburn 1301: }
1302: }
1303: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1304: ($is_balancer,$currtargets,$currrules) =
1305: &check_balancer_result($result,@hosts);
1.1129 raeburn 1306: if ($is_balancer) {
1307: if (ref($currrules) eq 'HASH') {
1308: if ($homeintdom) {
1309: if ($uname ne '') {
1310: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1311: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1312: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1313: $rule_in_effect = $currrules->{'_LC_author'};
1314: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1315: $rule_in_effect = $currrules->{'_LC_adv'}
1316: }
1317: }
1318: if ($rule_in_effect eq '') {
1319: my %userenv = &userenvironment($udom,$uname,'inststatus');
1320: if ($userenv{'inststatus'} ne '') {
1321: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1322: my ($othertitle,$usertypes,$types) =
1323: &Apache::loncommon::sorted_inst_types($udom);
1324: if (ref($types) eq 'ARRAY') {
1325: foreach my $type (@{$types}) {
1326: if (grep(/^\Q$type\E$/,@statuses)) {
1327: if (exists($currrules->{$type})) {
1328: $rule_in_effect = $currrules->{$type};
1329: }
1330: }
1331: }
1332: }
1333: } else {
1334: if (exists($currrules->{'default'})) {
1335: $rule_in_effect = $currrules->{'default'};
1336: }
1337: }
1338: }
1339: } else {
1340: if (exists($currrules->{'default'})) {
1341: $rule_in_effect = $currrules->{'default'};
1342: }
1343: }
1344: } else {
1345: if ($currrules->{'_LC_external'} ne '') {
1346: $rule_in_effect = $currrules->{'_LC_external'};
1347: }
1348: }
1349: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1350: $uname,$udom);
1351: }
1352: }
1353: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1354: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1355: unless (defined($cached)) {
1356: my %domconfig =
1357: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1358: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1359: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1360: }
1361: }
1362: if (ref($result) eq 'HASH') {
1.1172.2.12 raeburn 1363: ($is_balancer,$currtargets,$currrules) =
1364: &check_balancer_result($result,@hosts);
1365: if ($is_balancer) {
1.1129 raeburn 1366: if (ref($currrules) eq 'HASH') {
1367: if ($currrules->{'_LC_internetdom'} ne '') {
1368: $rule_in_effect = $currrules->{'_LC_internetdom'};
1369: }
1370: }
1371: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1372: $uname,$udom);
1373: }
1374: } else {
1375: if ($perlvar{'lonBalancer'} eq 'yes') {
1376: $is_balancer = 1;
1377: $offloadto = &this_host_spares($dom_in_use);
1378: }
1379: }
1380: } else {
1381: if ($perlvar{'lonBalancer'} eq 'yes') {
1382: $is_balancer = 1;
1383: $offloadto = &this_host_spares($dom_in_use);
1384: }
1385: }
1.1172.2.5 raeburn 1386: if ($is_balancer) {
1387: my $lowest_load = 30000;
1388: if (ref($offloadto) eq 'HASH') {
1389: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1390: foreach my $try_server (@{$offloadto->{'primary'}}) {
1391: ($otherserver,$lowest_load) =
1392: &compare_server_load($try_server,$otherserver,$lowest_load);
1393: }
1.1129 raeburn 1394: }
1.1172.2.5 raeburn 1395: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1396:
1.1172.2.5 raeburn 1397: if (!$found_server) {
1398: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1399: foreach my $try_server (@{$offloadto->{'default'}}) {
1400: ($otherserver,$lowest_load) =
1401: &compare_server_load($try_server,$otherserver,$lowest_load);
1402: }
1403: }
1404: }
1405: } elsif (ref($offloadto) eq 'ARRAY') {
1406: if (@{$offloadto} == 1) {
1407: $otherserver = $offloadto->[0];
1408: } elsif (@{$offloadto} > 1) {
1409: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1410: ($otherserver,$lowest_load) =
1411: &compare_server_load($try_server,$otherserver,$lowest_load);
1412: }
1413: }
1414: }
1.1172.2.5 raeburn 1415: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1416: $is_balancer = 0;
1417: if ($uname ne '' && $udom ne '') {
1418: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1419:
1420: &appenv({'user.loadbalexempt' => $lonhost,
1421: 'user.loadbalcheck.time' => time});
1422: }
1.1129 raeburn 1423: }
1424: }
1425: }
1426: return ($is_balancer,$otherserver);
1427: }
1428:
1.1172.2.12 raeburn 1429: sub check_balancer_result {
1430: my ($result,@hosts) = @_;
1431: my ($is_balancer,$currtargets,$currrules);
1432: if (ref($result) eq 'HASH') {
1433: if ($result->{'lonhost'} ne '') {
1434: my $currbalancer = $result->{'lonhost'};
1435: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1436: $is_balancer = 1;
1437: $currtargets = $result->{'targets'};
1438: $currrules = $result->{'rules'};
1439: }
1440: } else {
1441: foreach my $key (keys(%{$result})) {
1442: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1443: (ref($result->{$key}) eq 'HASH')) {
1444: $is_balancer = 1;
1445: $currrules = $result->{$key}{'rules'};
1446: $currtargets = $result->{$key}{'targets'};
1447: last;
1448: }
1449: }
1450: }
1451: }
1452: return ($is_balancer,$currtargets,$currrules);
1453: }
1454:
1.1129 raeburn 1455: sub get_loadbalancer_targets {
1456: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1457: my $offloadto;
1.1172.2.4 raeburn 1458: if ($rule_in_effect eq 'none') {
1459: return [$perlvar{'lonHostID'}];
1460: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1461: $offloadto = $currtargets;
1462: } else {
1463: if ($rule_in_effect eq 'homeserver') {
1464: my $homeserver = &homeserver($uname,$udom);
1465: if ($homeserver ne 'no_host') {
1466: $offloadto = [$homeserver];
1467: }
1468: } elsif ($rule_in_effect eq 'externalbalancer') {
1469: my %domconfig =
1470: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1471: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1472: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1473: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1474: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1475: }
1476: }
1477: } else {
1.1172.2.7 raeburn 1478: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1479: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1480: if (&hostname($remotebalancer) ne '') {
1481: $offloadto = [$remotebalancer];
1482: }
1483: }
1484: } elsif (&hostname($rule_in_effect) ne '') {
1485: $offloadto = [$rule_in_effect];
1486: }
1487: }
1488: return $offloadto;
1489: }
1490:
1.1127 raeburn 1491: sub internet_dom_servers {
1492: my ($dom) = @_;
1493: my (%uniqservers,%servers);
1494: my $primaryserver = &hostname(&domain($dom,'primary'));
1495: my @machinedoms = &machine_domains($primaryserver);
1496: foreach my $mdom (@machinedoms) {
1497: my %currservers = %servers;
1498: my %server = &get_servers($mdom);
1499: %servers = (%currservers,%server);
1500: }
1501: my %by_hostname;
1502: foreach my $id (keys(%servers)) {
1503: push(@{$by_hostname{$servers{$id}}},$id);
1504: }
1505: foreach my $hostname (sort(keys(%by_hostname))) {
1506: if (@{$by_hostname{$hostname}} > 1) {
1507: my $match = 0;
1508: foreach my $id (@{$by_hostname{$hostname}}) {
1509: if (&host_domain($id) eq $dom) {
1510: $uniqservers{$id} = $hostname;
1511: $match = 1;
1512: }
1513: }
1514: unless ($match) {
1515: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1516: }
1517: } else {
1518: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1519: }
1520: }
1521: return %uniqservers;
1522: }
1523:
1.1 albertel 1524: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1525:
1.599 albertel 1526: my %homecache;
1.1 albertel 1527: sub homeserver {
1.230 stredwic 1528: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1529: my $index="$uname:$udom";
1.426 albertel 1530:
1.599 albertel 1531: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1532:
1533: my %servers = &get_servers($udom,'library');
1534: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1535: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1536: exists($badServerCache{$tryserver}));
1.841 albertel 1537:
1538: my $answer=reply("home:$udom:$uname",$tryserver);
1539: if ($answer eq 'found') {
1540: delete($badServerCache{$tryserver});
1541: return $homecache{$index}=$tryserver;
1542: } elsif ($answer eq 'no_host') {
1543: $badServerCache{$tryserver}=1;
1544: }
1.1 albertel 1545: }
1546: return 'no_host';
1.70 www 1547: }
1548:
1549: # ------------------------------------- Find the usernames behind a list of IDs
1550:
1551: sub idget {
1552: my ($udom,@ids)=@_;
1553: my %returnhash=();
1554:
1.841 albertel 1555: my %servers = &get_servers($udom,'library');
1556: foreach my $tryserver (keys(%servers)) {
1.1172.2.73! raeburn 1557: my $idlist=join('&', map { &escape($_); } @ids);
1.841 albertel 1558: $idlist=~tr/A-Z/a-z/;
1559: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1560: my @answer=();
1561: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1562: @answer=split(/\&/,$reply);
1563: } ;
1564: my $i;
1565: for ($i=0;$i<=$#ids;$i++) {
1566: if ($answer[$i]) {
1.1172.2.73! raeburn 1567: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841 albertel 1568: }
1569: }
1570: }
1.70 www 1571: return %returnhash;
1572: }
1573:
1574: # ------------------------------------- Find the IDs behind a list of usernames
1575:
1576: sub idrget {
1577: my ($udom,@unames)=@_;
1578: my %returnhash=();
1.800 albertel 1579: foreach my $uname (@unames) {
1580: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1581: }
1.70 www 1582: return %returnhash;
1583: }
1584:
1585: # ------------------------------- Store away a list of names and associated IDs
1586:
1587: sub idput {
1588: my ($udom,%ids)=@_;
1589: my %servers=();
1.800 albertel 1590: foreach my $uname (keys(%ids)) {
1591: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1592: my $uhom=&homeserver($uname,$udom);
1.70 www 1593: if ($uhom ne 'no_host') {
1.800 albertel 1594: my $id=&escape($ids{$uname});
1.70 www 1595: $id=~tr/A-Z/a-z/;
1.800 albertel 1596: my $esc_unam=&escape($uname);
1.70 www 1597: if ($servers{$uhom}) {
1.800 albertel 1598: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1599: } else {
1.800 albertel 1600: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1601: }
1602: }
1.191 harris41 1603: }
1.800 albertel 1604: foreach my $server (keys(%servers)) {
1605: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1606: }
1.344 www 1607: }
1608:
1.1172.2.30 raeburn 1609: # ---------------------------------------- Delete unwanted IDs from ids.db file
1610:
1611: sub iddel {
1612: my ($udom,$idshashref,$uhome)=@_;
1613: my %result=();
1614: unless (ref($idshashref) eq 'HASH') {
1615: return %result;
1616: }
1617: my %servers=();
1618: while (my ($id,$uname) = each(%{$idshashref})) {
1619: my $uhom;
1620: if ($uhome) {
1621: $uhom = $uhome;
1622: } else {
1623: $uhom=&homeserver($uname,$udom);
1624: }
1625: if ($uhom ne 'no_host') {
1626: if ($servers{$uhom}) {
1627: $servers{$uhom}.='&'.&escape($id);
1628: } else {
1629: $servers{$uhom}=&escape($id);
1630: }
1631: }
1632: }
1633: foreach my $server (keys(%servers)) {
1634: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1635: }
1636: return %result;
1637: }
1638:
1.1023 raeburn 1639: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1640: sub dump_dom {
1.1165 droeschl 1641: my ($namespace, $udom, $regexp) = @_;
1642:
1643: $udom ||= $env{'user.domain'};
1644:
1645: return () unless $udom;
1646:
1647: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1648: }
1649:
1.1023 raeburn 1650: # ------------------------------------------ get items from domain db files
1.806 raeburn 1651:
1652: sub get_dom {
1.860 raeburn 1653: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57 raeburn 1654: return if ($udom eq 'public');
1.806 raeburn 1655: my $items='';
1656: foreach my $item (@$storearr) {
1657: $items.=&escape($item).'&';
1658: }
1659: $items=~s/\&$//;
1.860 raeburn 1660: if (!$udom) {
1661: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1662: return if ($udom eq 'public');
1.860 raeburn 1663: if (defined(&domain($udom,'primary'))) {
1664: $uhome=&domain($udom,'primary');
1665: } else {
1.874 albertel 1666: undef($uhome);
1.860 raeburn 1667: }
1668: } else {
1669: if (!$uhome) {
1670: if (defined(&domain($udom,'primary'))) {
1671: $uhome=&domain($udom,'primary');
1672: }
1673: }
1674: }
1675: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1676: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1677: my %returnhash;
1.875 albertel 1678: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1679: return %returnhash;
1680: }
1.806 raeburn 1681: my @pairs=split(/\&/,$rep);
1682: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1683: return @pairs;
1684: }
1685: my $i=0;
1686: foreach my $item (@$storearr) {
1687: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1688: $i++;
1689: }
1690: return %returnhash;
1691: } else {
1.880 banghart 1692: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1693: }
1694: }
1695:
1696: # -------------------------------------------- put items in domain db files
1697:
1698: sub put_dom {
1.860 raeburn 1699: my ($namespace,$storehash,$udom,$uhome)=@_;
1700: if (!$udom) {
1701: $udom=$env{'user.domain'};
1702: if (defined(&domain($udom,'primary'))) {
1703: $uhome=&domain($udom,'primary');
1704: } else {
1.874 albertel 1705: undef($uhome);
1.860 raeburn 1706: }
1707: } else {
1708: if (!$uhome) {
1709: if (defined(&domain($udom,'primary'))) {
1710: $uhome=&domain($udom,'primary');
1711: }
1712: }
1713: }
1714: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1715: my $items='';
1716: foreach my $item (keys(%$storehash)) {
1717: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1718: }
1719: $items=~s/\&$//;
1720: return &reply("putdom:$udom:$namespace:$items",$uhome);
1721: } else {
1.860 raeburn 1722: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1723: }
1724: }
1725:
1.1023 raeburn 1726: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1727: sub newput_dom {
1.1023 raeburn 1728: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1729: my $result;
1730: if (!$udom) {
1731: $udom=$env{'user.domain'};
1732: }
1.1023 raeburn 1733: if ($udom) {
1734: my $uname = &get_domainconfiguser($udom);
1735: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1736: }
1737: return $result;
1738: }
1739:
1.1023 raeburn 1740: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1741: sub del_dom {
1.1023 raeburn 1742: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1743: if (ref($storearr) eq 'ARRAY') {
1744: if (!$udom) {
1745: $udom=$env{'user.domain'};
1746: }
1.1023 raeburn 1747: if ($udom) {
1748: my $uname = &get_domainconfiguser($udom);
1749: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1750: }
1751: }
1752: }
1753:
1.1023 raeburn 1754: # ----------------------------------construct domainconfig user for a domain
1755: sub get_domainconfiguser {
1756: my ($udom) = @_;
1757: return $udom.'-domainconfig';
1758: }
1759:
1.837 raeburn 1760: sub retrieve_inst_usertypes {
1761: my ($udom) = @_;
1762: my (%returnhash,@order);
1.989 raeburn 1763: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1764: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1765: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 1766: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1767: } else {
1768: if (defined(&domain($udom,'primary'))) {
1769: my $uhome=&domain($udom,'primary');
1770: my $rep=&reply("inst_usertypes:$udom",$uhome);
1771: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 1772: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1773: return (\%returnhash,\@order);
1774: }
1775: my ($hashitems,$orderitems) = split(/:/,$rep);
1776: my @pairs=split(/\&/,$hashitems);
1777: foreach my $item (@pairs) {
1778: my ($key,$value)=split(/=/,$item,2);
1779: $key = &unescape($key);
1780: next if ($key =~ /^error: 2 /);
1781: $returnhash{$key}=&thaw_unescape($value);
1782: }
1783: my @esc_order = split(/\&/,$orderitems);
1784: foreach my $item (@esc_order) {
1785: push(@order,&unescape($item));
1786: }
1787: } else {
1.1172.2.44 raeburn 1788: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1789: }
1.1172.2.44 raeburn 1790: return (\%returnhash,\@order);
1.837 raeburn 1791: }
1792: }
1793:
1.868 raeburn 1794: sub is_domainimage {
1795: my ($url) = @_;
1796: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1797: if (&domain($1) ne '') {
1798: return '1';
1799: }
1800: }
1801: return;
1802: }
1803:
1.899 raeburn 1804: sub inst_directory_query {
1805: my ($srch) = @_;
1806: my $udom = $srch->{'srchdomain'};
1807: my %results;
1808: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1809: my $outcome;
1.899 raeburn 1810: if ($homeserver ne '') {
1.904 albertel 1811: my $queryid=&reply("querysend:instdirsearch:".
1812: &escape($srch->{'srchby'}).':'.
1813: &escape($srch->{'srchterm'}).':'.
1814: &escape($srch->{'srchtype'}),$homeserver);
1815: my $host=&hostname($homeserver);
1816: if ($queryid !~/^\Q$host\E\_/) {
1817: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1818: return;
1819: }
1820: my $response = &get_query_reply($queryid);
1821: my $maxtries = 5;
1822: my $tries = 1;
1823: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1824: $response = &get_query_reply($queryid);
1825: $tries ++;
1826: }
1827:
1828: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1829: if ($response eq 'unavailable') {
1830: $outcome = $response;
1831: } else {
1832: $outcome = 'ok';
1833: my @matches = split(/\n/,$response);
1834: foreach my $match (@matches) {
1835: my ($key,$value) = split(/=/,$match);
1836: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1837: }
1.899 raeburn 1838: }
1839: }
1840: }
1.909 raeburn 1841: return ($outcome,%results);
1.899 raeburn 1842: }
1843:
1844: sub usersearch {
1845: my ($srch) = @_;
1846: my $dom = $srch->{'srchdomain'};
1847: my %results;
1848: my %libserv = &all_library();
1849: my $query = 'usersearch';
1850: foreach my $tryserver (keys(%libserv)) {
1851: if (&host_domain($tryserver) eq $dom) {
1852: my $host=&hostname($tryserver);
1853: my $queryid=
1.911 raeburn 1854: &reply("querysend:".&escape($query).':'.
1855: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1856: &escape($srch->{'srchtype'}).':'.
1857: &escape($srch->{'srchterm'}),$tryserver);
1858: if ($queryid !~/^\Q$host\E\_/) {
1859: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1860: next;
1.899 raeburn 1861: }
1862: my $reply = &get_query_reply($queryid);
1863: my $maxtries = 1;
1864: my $tries = 1;
1865: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1866: $reply = &get_query_reply($queryid);
1867: $tries ++;
1868: }
1869: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1870: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1871: } else {
1.911 raeburn 1872: my @matches;
1873: if ($reply =~ /\n/) {
1874: @matches = split(/\n/,$reply);
1875: } else {
1876: @matches = split(/\&/,$reply);
1877: }
1.899 raeburn 1878: foreach my $match (@matches) {
1879: my ($uname,$udom,%userhash);
1.911 raeburn 1880: foreach my $entry (split(/:/,$match)) {
1881: my ($key,$value) =
1882: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1883: $userhash{$key} = $value;
1884: if ($key eq 'username') {
1885: $uname = $value;
1886: } elsif ($key eq 'domain') {
1887: $udom = $value;
1.911 raeburn 1888: }
1.899 raeburn 1889: }
1890: $results{$uname.':'.$udom} = \%userhash;
1891: }
1892: }
1893: }
1894: }
1895: return %results;
1896: }
1897:
1.912 raeburn 1898: sub get_instuser {
1899: my ($udom,$uname,$id) = @_;
1900: my $homeserver = &domain($udom,'primary');
1901: my ($outcome,%results);
1902: if ($homeserver ne '') {
1903: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1904: &escape($id).':'.&escape($udom),$homeserver);
1905: my $host=&hostname($homeserver);
1906: if ($queryid !~/^\Q$host\E\_/) {
1907: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1908: return;
1909: }
1910: my $response = &get_query_reply($queryid);
1911: my $maxtries = 5;
1912: my $tries = 1;
1913: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1914: $response = &get_query_reply($queryid);
1915: $tries ++;
1916: }
1917: if (!&error($response) && $response ne 'refused') {
1918: if ($response eq 'unavailable') {
1919: $outcome = $response;
1920: } else {
1921: $outcome = 'ok';
1922: my @matches = split(/\n/,$response);
1923: foreach my $match (@matches) {
1924: my ($key,$value) = split(/=/,$match);
1925: $results{&unescape($key)} = &thaw_unescape($value);
1926: }
1927: }
1928: }
1929: }
1930: my %userinfo;
1931: if (ref($results{$uname}) eq 'HASH') {
1932: %userinfo = %{$results{$uname}};
1933: }
1934: return ($outcome,%userinfo);
1935: }
1936:
1.1172.2.69 raeburn 1937: sub get_multiple_instusers {
1938: my ($udom,$users,$caller) = @_;
1939: my ($outcome,$results);
1940: if (ref($users) eq 'HASH') {
1941: my $count = keys(%{$users});
1942: my $requested = &freeze_escape($users);
1943: my $homeserver = &domain($udom,'primary');
1944: if ($homeserver ne '') {
1945: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
1946: my $host=&hostname($homeserver);
1947: if ($queryid !~/^\Q$host\E\_/) {
1948: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
1949: ' for host: '.$homeserver.'in domain '.$udom);
1950: return ($outcome,$results);
1951: }
1952: my $response = &get_query_reply($queryid);
1953: my $maxtries = 5;
1954: if ($count > 100) {
1955: $maxtries = 1+int($count/20);
1956: }
1957: my $tries = 1;
1958: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
1959: $response = &get_query_reply($queryid);
1960: $tries ++;
1961: }
1962: if ($response eq '') {
1963: $results = {};
1964: foreach my $key (keys(%{$users})) {
1965: my ($uname,$id);
1966: if ($caller eq 'id') {
1967: $id = $key;
1968: } else {
1969: $uname = $key;
1970: }
1971: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1972: $outcome = $resp;
1973: if ($resp eq 'ok') {
1974: %{$results} = (%{$results}, %info);
1975: } else {
1976: last;
1977: }
1978: }
1979: } elsif(!&error($response) && ($response ne 'refused')) {
1980: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
1981: $outcome = $response;
1982: } else {
1983: ($outcome,my $userdata) = split(/=/,$response,2);
1984: if ($outcome eq 'ok') {
1985: $results = &thaw_unescape($userdata);
1986: }
1987: }
1988: }
1989: }
1990: }
1991: return ($outcome,$results);
1992: }
1993:
1.912 raeburn 1994: sub inst_rulecheck {
1.923 raeburn 1995: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1996: my %returnhash;
1997: if ($udom ne '') {
1998: if (ref($rules) eq 'ARRAY') {
1999: @{$rules} = map {&escape($_);} (@{$rules});
2000: my $rulestr = join(':',@{$rules});
2001: my $homeserver=&domain($udom,'primary');
2002: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2003: my $response;
2004: if ($item eq 'username') {
2005: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2006: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2007: $homeserver));
1.923 raeburn 2008: } elsif ($item eq 'id') {
2009: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2010: ':'.&escape($id).':'.$rulestr,
2011: $homeserver));
1.945 raeburn 2012: } elsif ($item eq 'selfcreate') {
2013: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2014: &escape($udom).':'.&escape($uname).
2015: ':'.$rulestr,$homeserver));
1.923 raeburn 2016: }
1.912 raeburn 2017: if ($response ne 'refused') {
2018: my @pairs=split(/\&/,$response);
2019: foreach my $item (@pairs) {
2020: my ($key,$value)=split(/=/,$item,2);
2021: $key = &unescape($key);
2022: next if ($key =~ /^error: 2 /);
2023: $returnhash{$key}=&thaw_unescape($value);
2024: }
2025: }
2026: }
2027: }
2028: }
2029: return %returnhash;
2030: }
2031:
2032: sub inst_userrules {
1.923 raeburn 2033: my ($udom,$check) = @_;
1.912 raeburn 2034: my (%ruleshash,@ruleorder);
2035: if ($udom ne '') {
2036: my $homeserver=&domain($udom,'primary');
2037: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2038: my $response;
2039: if ($check eq 'id') {
2040: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2041: $homeserver);
1.943 raeburn 2042: } elsif ($check eq 'email') {
2043: $response=&reply('instemailrules:'.&escape($udom),
2044: $homeserver);
1.923 raeburn 2045: } else {
2046: $response=&reply('instuserrules:'.&escape($udom),
2047: $homeserver);
2048: }
1.912 raeburn 2049: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2050: ($response ne 'unknown_cmd') &&
1.912 raeburn 2051: ($response ne 'no_such_host')) {
2052: my ($hashitems,$orderitems) = split(/:/,$response);
2053: my @pairs=split(/\&/,$hashitems);
2054: foreach my $item (@pairs) {
2055: my ($key,$value)=split(/=/,$item,2);
2056: $key = &unescape($key);
2057: next if ($key =~ /^error: 2 /);
2058: $ruleshash{$key}=&thaw_unescape($value);
2059: }
2060: my @esc_order = split(/\&/,$orderitems);
2061: foreach my $item (@esc_order) {
2062: push(@ruleorder,&unescape($item));
2063: }
2064: }
2065: }
2066: }
2067: return (\%ruleshash,\@ruleorder);
2068: }
2069:
1.976 raeburn 2070: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2071:
2072: sub get_domain_defaults {
1.1172.2.35 raeburn 2073: my ($domain,$ignore_cache) = @_;
2074: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2075: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2076: unless ($ignore_cache) {
2077: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2078: if (defined($cached)) {
2079: if (ref($result) eq 'HASH') {
2080: return %{$result};
2081: }
1.943 raeburn 2082: }
2083: }
2084: my %domdefaults;
2085: my %domconfig =
1.989 raeburn 2086: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2087: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2088: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2089: 'requestauthor','selfenrollment',
2090: 'coursecategories'],$domain);
1.1172.2.41 raeburn 2091: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2092: if (ref($domconfig{'defaults'}) eq 'HASH') {
2093: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2094: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2095: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2096: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2097: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2098: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2099: } else {
2100: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2101: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2102: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2103: }
1.976 raeburn 2104: if (ref($domconfig{'quotas'}) eq 'HASH') {
2105: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2106: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2107: } else {
2108: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2109: }
1.1172.2.6 raeburn 2110: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2111: foreach my $item (@usertools) {
2112: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2113: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2114: }
2115: }
1.1172.2.29 raeburn 2116: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2117: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2118: }
1.976 raeburn 2119: }
1.985 raeburn 2120: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2121: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2122: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2123: }
2124: }
1.1172.2.9 raeburn 2125: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2126: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2127: }
1.989 raeburn 2128: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2129: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2130: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2131: }
2132: }
1.1047 raeburn 2133: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2134: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2135: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2136: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2137: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2138: }
1.1172.2.41 raeburn 2139: foreach my $type (@coursetypes) {
2140: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2141: unless ($type eq 'community') {
2142: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2143: }
2144: }
2145: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2146: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2147: }
1.1172.2.60 raeburn 2148: if ($domdefaults{'postsubmit'} eq 'on') {
2149: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2150: $domdefaults{$type.'postsubtimeout'} =
2151: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2152: }
2153: }
1.1172.2.30 raeburn 2154: }
1.1172.2.67 raeburn 2155: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2156: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2157: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2158: if (@clonecodes) {
2159: $domdefaults{'canclone'} = join('+',@clonecodes);
2160: }
2161: }
2162: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2163: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2164: }
1.1047 raeburn 2165: }
1.1073 raeburn 2166: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2167: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2168: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2169: }
2170: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2171: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2172: }
1.1172.2.62 raeburn 2173: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2174: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2175: }
1.1073 raeburn 2176: }
1.1172.2.41 raeburn 2177: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2178: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2179: my @settings = ('types','registered','enroll_dates','access_dates','section',
2180: 'approval','limit');
2181: foreach my $type (@coursetypes) {
2182: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2183: my @mgrdc = ();
2184: foreach my $item (@settings) {
2185: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2186: push(@mgrdc,$item);
2187: }
2188: }
2189: if (@mgrdc) {
2190: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2191: }
2192: }
2193: }
2194: }
2195: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2196: foreach my $type (@coursetypes) {
2197: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2198: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2199: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2200: }
2201: }
2202: }
2203: }
2204: }
1.1172.2.46 raeburn 2205: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2206: $domdefaults{'catauth'} = 'std';
2207: $domdefaults{'catunauth'} = 'std';
2208: if ($domconfig{'coursecategories'}{'auth'}) {
2209: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2210: }
2211: if ($domconfig{'coursecategories'}{'unauth'}) {
2212: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2213: }
2214: }
1.1172.2.23 raeburn 2215: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2216: return %domdefaults;
2217: }
2218:
1.344 www 2219: # --------------------------------------------------- Assign a key to a student
2220:
2221: sub assign_access_key {
1.364 www 2222: #
2223: # a valid key looks like uname:udom#comments
2224: # comments are being appended
2225: #
1.498 www 2226: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2227: $kdom=
1.620 albertel 2228: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2229: $knum=
1.620 albertel 2230: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2231: $cdom=
1.620 albertel 2232: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2233: $cnum=
1.620 albertel 2234: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2235: $udom=$env{'user.name'} unless (defined($udom));
2236: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2237: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2238: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2239: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2240: # assigned to this person
2241: # - this should not happen,
1.345 www 2242: # unless something went wrong
2243: # the first time around
2244: # ready to assign
1.364 www 2245: $logentry=$1.'; '.$logentry;
1.496 www 2246: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2247: $kdom,$knum) eq 'ok') {
1.345 www 2248: # key now belongs to user
1.346 www 2249: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2250: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2251: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2252: return 'ok';
2253: } else {
2254: return
2255: 'error: Count not permanently assign key, will need to be re-entered later.';
2256: }
2257: } else {
2258: return 'error: Could not assign key, try again later.';
2259: }
1.364 www 2260: } elsif (!$existing{$ckey}) {
1.345 www 2261: # the key does not exist
2262: return 'error: The key does not exist';
2263: } else {
2264: # the key is somebody else's
2265: return 'error: The key is already in use';
2266: }
1.344 www 2267: }
2268:
1.364 www 2269: # ------------------------------------------ put an additional comment on a key
2270:
2271: sub comment_access_key {
2272: #
2273: # a valid key looks like uname:udom#comments
2274: # comments are being appended
2275: #
2276: my ($ckey,$cdom,$cnum,$logentry)=@_;
2277: $cdom=
1.620 albertel 2278: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2279: $cnum=
1.620 albertel 2280: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2281: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2282: if ($existing{$ckey}) {
2283: $existing{$ckey}.='; '.$logentry;
2284: # ready to assign
1.367 www 2285: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2286: $cdom,$cnum) eq 'ok') {
2287: return 'ok';
2288: } else {
2289: return 'error: Count not store comment.';
2290: }
2291: } else {
2292: # the key does not exist
2293: return 'error: The key does not exist';
2294: }
2295: }
2296:
1.344 www 2297: # ------------------------------------------------------ Generate a set of keys
2298:
2299: sub generate_access_keys {
1.364 www 2300: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2301: $cdom=
1.620 albertel 2302: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2303: $cnum=
1.620 albertel 2304: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2305: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2306: unless (($cdom) && ($cnum)) { return 0; }
2307: if ($number>10000) { return 0; }
2308: sleep(2); # make sure don't get same seed twice
2309: srand(time()^($$+($$<<15))); # from "Programming Perl"
2310: my $total=0;
2311: for (my $i=1;$i<=$number;$i++) {
2312: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2313: sprintf("%lx",int(100000*rand)).'-'.
2314: sprintf("%lx",int(100000*rand));
2315: $newkey=~s/1/g/g; # folks mix up 1 and l
2316: $newkey=~s/0/h/g; # and also 0 and O
2317: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2318: if ($existing{$newkey}) {
2319: $i--;
2320: } else {
1.364 www 2321: if (&put('accesskeys',
2322: { $newkey => '# generated '.localtime().
1.620 albertel 2323: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2324: '; '.$logentry },
2325: $cdom,$cnum) eq 'ok') {
1.344 www 2326: $total++;
2327: }
2328: }
2329: }
1.620 albertel 2330: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2331: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2332: return $total;
2333: }
2334:
2335: # ------------------------------------------------------- Validate an accesskey
2336:
2337: sub validate_access_key {
2338: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2339: $cdom=
1.620 albertel 2340: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2341: $cnum=
1.620 albertel 2342: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2343: $udom=$env{'user.domain'} unless (defined($udom));
2344: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2345: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2346: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2347: }
2348:
2349: # ------------------------------------- Find the section of student in a course
1.652 albertel 2350: sub devalidate_getsection_cache {
2351: my ($udom,$unam,$courseid)=@_;
2352: my $hashid="$udom:$unam:$courseid";
2353: &devalidate_cache_new('getsection',$hashid);
2354: }
1.298 matthew 2355:
1.815 albertel 2356: sub courseid_to_courseurl {
2357: my ($courseid) = @_;
2358: #already url style courseid
2359: return $courseid if ($courseid =~ m{^/});
2360:
2361: if (exists($env{'course.'.$courseid.'.num'})) {
2362: my $cnum = $env{'course.'.$courseid.'.num'};
2363: my $cdom = $env{'course.'.$courseid.'.domain'};
2364: return "/$cdom/$cnum";
2365: }
2366:
2367: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2368: if (exists($courseinfo{'num'})) {
2369: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2370: }
2371:
2372: return undef;
2373: }
2374:
1.298 matthew 2375: sub getsection {
2376: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2377: my $cachetime=1800;
1.551 albertel 2378:
2379: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2380: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2381: if (defined($cached)) { return $result; }
2382:
1.298 matthew 2383: my %Pending;
2384: my %Expired;
2385: #
2386: # Each role can either have not started yet (pending), be active,
2387: # or have expired.
2388: #
2389: # If there is an active role, we are done.
2390: #
2391: # If there is more than one role which has not started yet,
2392: # choose the one which will start sooner
2393: # If there is one role which has not started yet, return it.
2394: #
2395: # If there is more than one expired role, choose the one which ended last.
2396: # If there is a role which has expired, return it.
2397: #
1.815 albertel 2398: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2399: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2400: foreach my $key (keys(%roleshash)) {
1.479 albertel 2401: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2402: my $section=$1;
2403: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2404: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2405: my $now=time;
1.548 albertel 2406: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2407: $Expired{$end}=$section;
2408: next;
2409: }
1.548 albertel 2410: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2411: $Pending{$start}=$section;
2412: next;
2413: }
1.599 albertel 2414: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2415: }
2416: #
2417: # Presumedly there will be few matching roles from the above
2418: # loop and the sorting time will be negligible.
2419: if (scalar(keys(%Pending))) {
2420: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2421: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2422: }
2423: if (scalar(keys(%Expired))) {
2424: my @sorted = sort {$a <=> $b} keys(%Expired);
2425: my $time = pop(@sorted);
1.599 albertel 2426: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2427: }
1.599 albertel 2428: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2429: }
1.70 www 2430:
1.599 albertel 2431: sub save_cache {
2432: &purge_remembered();
1.722 albertel 2433: #&Apache::loncommon::validate_page();
1.620 albertel 2434: undef(%env);
1.780 albertel 2435: undef($env_loaded);
1.599 albertel 2436: }
1.452 albertel 2437:
1.599 albertel 2438: my $to_remember=-1;
2439: my %remembered;
2440: my %accessed;
2441: my $kicks=0;
2442: my $hits=0;
1.849 albertel 2443: sub make_key {
2444: my ($name,$id) = @_;
1.872 albertel 2445: if (length($id) > 65
2446: && length(&escape($id)) > 200) {
2447: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2448: }
1.849 albertel 2449: return &escape($name.':'.$id);
2450: }
2451:
1.599 albertel 2452: sub devalidate_cache_new {
2453: my ($name,$id,$debug) = @_;
2454: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2455: $id=&make_key($name,$id);
1.599 albertel 2456: $memcache->delete($id);
2457: delete($remembered{$id});
2458: delete($accessed{$id});
2459: }
2460:
2461: sub is_cached_new {
2462: my ($name,$id,$debug) = @_;
1.849 albertel 2463: $id=&make_key($name,$id);
1.599 albertel 2464: if (exists($remembered{$id})) {
1.1133 foxr 2465: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2466: $accessed{$id}=[&gettimeofday()];
2467: $hits++;
2468: return ($remembered{$id},1);
2469: }
2470: my $value = $memcache->get($id);
2471: if (!(defined($value))) {
2472: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2473: return (undef,undef);
1.416 albertel 2474: }
1.599 albertel 2475: if ($value eq '__undef__') {
2476: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2477: $value=undef;
2478: }
2479: &make_room($id,$value,$debug);
2480: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2481: return ($value,1);
2482: }
2483:
2484: sub do_cache_new {
2485: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2486: $id=&make_key($name,$id);
1.599 albertel 2487: my $setvalue=$value;
2488: if (!defined($setvalue)) {
2489: $setvalue='__undef__';
2490: }
1.623 albertel 2491: if (!defined($time) ) {
2492: $time=600;
2493: }
1.599 albertel 2494: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2495: my $result = $memcache->set($id,$setvalue,$time);
2496: if (! $result) {
1.872 albertel 2497: &logthis("caching of id -> $id failed");
1.910 albertel 2498: $memcache->disconnect_all();
1.872 albertel 2499: }
1.600 albertel 2500: # need to make a copy of $value
1.919 albertel 2501: &make_room($id,$value,$debug);
1.599 albertel 2502: return $value;
2503: }
2504:
2505: sub make_room {
2506: my ($id,$value,$debug)=@_;
1.919 albertel 2507:
2508: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2509: : $value;
1.599 albertel 2510: if ($to_remember<0) { return; }
2511: $accessed{$id}=[&gettimeofday()];
2512: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2513: my $to_kick;
2514: my $max_time=0;
2515: foreach my $other (keys(%accessed)) {
2516: if (&tv_interval($accessed{$other}) > $max_time) {
2517: $to_kick=$other;
2518: $max_time=&tv_interval($accessed{$other});
2519: }
2520: }
2521: delete($remembered{$to_kick});
2522: delete($accessed{$to_kick});
2523: $kicks++;
2524: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2525: return;
2526: }
2527:
1.599 albertel 2528: sub purge_remembered {
1.604 albertel 2529: #&logthis("Tossing ".scalar(keys(%remembered)));
2530: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2531: undef(%remembered);
2532: undef(%accessed);
1.428 albertel 2533: }
1.70 www 2534: # ------------------------------------- Read an entry from a user's environment
2535:
2536: sub userenvironment {
2537: my ($udom,$unam,@what)=@_;
1.976 raeburn 2538: my $items;
2539: foreach my $item (@what) {
2540: $items.=&escape($item).'&';
2541: }
2542: $items=~s/\&$//;
1.70 www 2543: my %returnhash=();
1.1009 raeburn 2544: my $uhome = &homeserver($unam,$udom);
2545: unless ($uhome eq 'no_host') {
2546: my @answer=split(/\&/,
2547: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2548: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2549: return %returnhash;
2550: }
1.1009 raeburn 2551: my $i;
2552: for ($i=0;$i<=$#what;$i++) {
2553: $returnhash{$what[$i]}=&unescape($answer[$i]);
2554: }
1.70 www 2555: }
2556: return %returnhash;
1.1 albertel 2557: }
2558:
1.617 albertel 2559: # ---------------------------------------------------------- Get a studentphoto
2560: sub studentphoto {
2561: my ($udom,$unam,$ext) = @_;
2562: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2563: if (defined($env{'request.course.id'})) {
1.708 raeburn 2564: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2565: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2566: return(&retrievestudentphoto($udom,$unam,$ext));
2567: } else {
2568: my ($result,$perm_reqd)=
1.707 albertel 2569: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2570: if ($result eq 'ok') {
2571: if (!($perm_reqd eq 'yes')) {
2572: return(&retrievestudentphoto($udom,$unam,$ext));
2573: }
2574: }
2575: }
2576: }
2577: } else {
2578: my ($result,$perm_reqd) =
1.707 albertel 2579: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2580: if ($result eq 'ok') {
2581: if (!($perm_reqd eq 'yes')) {
2582: return(&retrievestudentphoto($udom,$unam,$ext));
2583: }
2584: }
2585: }
2586: return '/adm/lonKaputt/lonlogo_broken.gif';
2587: }
2588:
2589: sub retrievestudentphoto {
2590: my ($udom,$unam,$ext,$type) = @_;
2591: my $home=&Apache::lonnet::homeserver($unam,$udom);
2592: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2593: if ($ret eq 'ok') {
2594: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2595: if ($type eq 'thumbnail') {
2596: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2597: }
2598: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2599: return $tokenurl;
2600: } else {
2601: if ($type eq 'thumbnail') {
2602: return '/adm/lonKaputt/genericstudent_tn.gif';
2603: } else {
2604: return '/adm/lonKaputt/lonlogo_broken.gif';
2605: }
1.617 albertel 2606: }
2607: }
2608:
1.263 www 2609: # -------------------------------------------------------------------- New chat
2610:
2611: sub chatsend {
1.724 raeburn 2612: my ($newentry,$anon,$group)=@_;
1.620 albertel 2613: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2614: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2615: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2616: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2617: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2618: &escape($newentry)).':'.$group,$chome);
1.292 www 2619: }
2620:
2621: # ------------------------------------------ Find current version of a resource
2622:
2623: sub getversion {
2624: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2625: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2626: return ¤tversion(&filelocation('',$fname));
2627: }
2628:
2629: sub currentversion {
2630: my $fname=shift;
2631: my $author=$fname;
2632: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2633: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2634: my $home=&homeserver($uname,$udom);
1.292 www 2635: if ($home eq 'no_host') {
2636: return -1;
2637: }
1.1112 www 2638: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2639: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2640: return -1;
2641: }
1.1112 www 2642: return $answer;
1.263 www 2643: }
2644:
1.1111 www 2645: #
2646: # Return special version number of resource if set by override, empty otherwise
2647: #
2648: sub usedversion {
2649: my $fname=shift;
2650: unless ($fname) { $fname=$env{'request.uri'}; }
2651: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2652: if ($urlversion) { return $urlversion; }
2653: return '';
2654: }
2655:
1.1 albertel 2656: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2657:
1.1 albertel 2658: sub subscribe {
2659: my $fname=shift;
1.761 raeburn 2660: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2661: $fname=~s/[\n\r]//g;
1.1 albertel 2662: my $author=$fname;
2663: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2664: my ($udom,$uname)=split(/\//,$author);
2665: my $home=homeserver($uname,$udom);
1.335 albertel 2666: if ($home eq 'no_host') {
2667: return 'not_found';
1.1 albertel 2668: }
2669: my $answer=reply("sub:$fname",$home);
1.64 www 2670: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2671: $answer.=' by '.$home;
2672: }
1.1 albertel 2673: return $answer;
2674: }
2675:
1.8 www 2676: # -------------------------------------------------------------- Replicate file
2677:
2678: sub repcopy {
2679: my $filename=shift;
1.23 www 2680: $filename=~s/\/+/\//g;
1.1142 raeburn 2681: my $londocroot = $perlvar{'lonDocRoot'};
2682: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2683: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2684: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2685: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2686: return &repcopy_userfile($filename);
2687: }
1.532 albertel 2688: $filename=~s/[\n\r]//g;
1.8 www 2689: my $transname="$filename.in.transfer";
1.828 www 2690: # FIXME: this should flock
1.607 raeburn 2691: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2692: my $remoteurl=subscribe($filename);
1.64 www 2693: if ($remoteurl =~ /^con_lost by/) {
2694: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2695: return 'unavailable';
1.8 www 2696: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2697: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2698: return 'not_found';
1.64 www 2699: } elsif ($remoteurl =~ /^rejected by/) {
2700: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2701: return 'forbidden';
1.20 www 2702: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2703: return 'ok';
1.8 www 2704: } else {
1.290 www 2705: my $author=$filename;
2706: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2707: my ($udom,$uname)=split(/\//,$author);
2708: my $home=homeserver($uname,$udom);
2709: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2710: my @parts=split(/\//,$filename);
2711: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2712: if ($path ne "$londocroot/res") {
1.8 www 2713: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2714: return 'bad_request';
1.8 www 2715: }
2716: my $count;
2717: for ($count=5;$count<$#parts;$count++) {
2718: $path.="/$parts[$count]";
2719: if ((-e $path)!=1) {
2720: mkdir($path,0777);
2721: }
2722: }
2723: my $ua=new LWP::UserAgent;
2724: my $request=new HTTP::Request('GET',"$remoteurl");
2725: my $response=$ua->request($request,$transname);
2726: if ($response->is_error()) {
2727: unlink($transname);
2728: my $message=$response->status_line;
1.672 albertel 2729: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2730: ." LWP get: $message: $filename</font>");
1.607 raeburn 2731: return 'unavailable';
1.8 www 2732: } else {
1.16 www 2733: if ($remoteurl!~/\.meta$/) {
2734: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2735: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2736: if ($mresponse->is_error()) {
2737: unlink($filename.'.meta');
2738: &logthis(
1.672 albertel 2739: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2740: }
2741: }
1.8 www 2742: rename($transname,$filename);
1.607 raeburn 2743: return 'ok';
1.8 www 2744: }
1.290 www 2745: }
1.8 www 2746: }
1.330 www 2747: }
2748:
2749: # ------------------------------------------------ Get server side include body
2750: sub ssi_body {
1.381 albertel 2751: my ($filelink,%form)=@_;
1.606 matthew 2752: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2753: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2754: }
1.953 www 2755: my $output='';
2756: my $response;
1.980 raeburn 2757: if ($filelink=~/^https?\:/) {
1.954 raeburn 2758: ($output,$response)=&externalssi($filelink);
1.953 www 2759: } else {
1.1004 droeschl 2760: $filelink .= $filelink=~/\?/ ? '&' : '?';
2761: $filelink .= 'inhibitmenu=yes';
1.953 www 2762: ($output,$response)=&ssi($filelink,%form);
2763: }
1.778 albertel 2764: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2765: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2766: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2767: if (wantarray) {
2768: return ($output, $response);
2769: } else {
2770: return $output;
2771: }
1.8 www 2772: }
2773:
1.15 www 2774: # --------------------------------------------------------- Server Side Include
2775:
1.782 albertel 2776: sub absolute_url {
2777: my ($host_name) = @_;
2778: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2779: if ($host_name eq '') {
2780: $host_name = $ENV{'SERVER_NAME'};
2781: }
2782: return $protocol.$host_name;
2783: }
2784:
1.942 foxr 2785: #
2786: # Server side include.
2787: # Parameters:
2788: # fn Possibly encrypted resource name/id.
2789: # form Hash that describes how the rendering should be done
2790: # and other things.
1.944 foxr 2791: # Returns:
1.950 raeburn 2792: # Scalar context: The content of the response.
2793: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2794: #
1.15 www 2795: sub ssi {
2796:
1.944 foxr 2797: my ($fn,%form)=@_;
1.15 www 2798: my $ua=new LWP::UserAgent;
1.23 www 2799: my $request;
1.711 albertel 2800:
2801: $form{'no_update_last_known'}=1;
1.895 albertel 2802: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2803: if (%form) {
1.782 albertel 2804: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58 raeburn 2805: $request->content(join('&',map {
2806: my $name = escape($_);
2807: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2808: ? join("&$name=", map {escape($_) } @{$form{$_}})
2809: : &escape($form{$_}) );
2810: } keys(%form)));
1.23 www 2811: } else {
1.782 albertel 2812: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2813: }
2814:
1.15 www 2815: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2816: my $response= $ua->request($request);
1.944 foxr 2817: if (wantarray) {
1.1172.2.3 raeburn 2818: return ($response->content, $response);
1.944 foxr 2819: } else {
1.1172.2.3 raeburn 2820: return $response->content;
1.942 foxr 2821: }
1.324 www 2822: }
2823:
2824: sub externalssi {
2825: my ($url)=@_;
2826: my $ua=new LWP::UserAgent;
2827: my $request=new HTTP::Request('GET',$url);
2828: my $response=$ua->request($request);
1.954 raeburn 2829: if (wantarray) {
2830: return ($response->content, $response);
2831: } else {
2832: return $response->content;
2833: }
1.15 www 2834: }
1.254 www 2835:
1.492 albertel 2836: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2837:
2838: sub allowuploaded {
2839: my ($srcurl,$url)=@_;
2840: $url=&clutter(&declutter($url));
2841: my $dir=$url;
2842: $dir=~s/\/[^\/]+$//;
2843: my %httpref=();
2844: my $httpurl=&hreflocation('',$url);
2845: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2846: &Apache::lonnet::appenv(\%httpref);
1.254 www 2847: }
1.477 raeburn 2848:
1.1172.2.13 raeburn 2849: #
2850: # Determine if the current user should be able to edit a particular resource,
2851: # when viewing in course context.
2852: # (a) When viewing resource used to determine if "Edit" item is included in
2853: # Functions.
2854: # (b) When displaying folder contents in course editor, used to determine if
2855: # "Edit" link will be displayed alongside resource.
2856: #
2857: # input: six args -- filename (decluttered), course number, course domain,
2858: # url, symb (if registered) and group (if this is a group
2859: # item -- e.g., bulletin board, group page etc.).
2860: # output: array of five scalars --
2861: # $cfile -- url for file editing if editable on current server
2862: # $home -- homeserver of resource (i.e., for author if published,
2863: # or course if uploaded.).
2864: # $switchserver -- 1 if server switch will be needed.
2865: # $forceedit -- 1 if icon/link should be to go to edit mode
2866: # $forceview -- 1 if icon/link should be to go to view mode
2867: #
2868:
2869: sub can_edit_resource {
2870: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2871: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2872: #
2873: # For aboutme pages user can only edit his/her own.
2874: #
2875: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2876: my ($sdom,$sname) = ($1,$2);
2877: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2878: $home = $env{'user.home'};
2879: $cfile = $resurl;
2880: if ($env{'form.forceedit'}) {
2881: $forceview = 1;
2882: } else {
2883: $forceedit = 1;
2884: }
2885: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2886: } else {
2887: return;
2888: }
2889: }
2890:
2891: if ($env{'request.course.id'}) {
2892: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2893: if ($group ne '') {
2894: # if this is a group homepage or group bulletin board, check group privs
2895: my $allowed = 0;
2896: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2897: if ((&allowed('mdg',$env{'request.course.id'}.
2898: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2899: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2900: $allowed = 1;
2901: }
2902: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2903: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2904: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2905: $allowed = 1;
2906: }
2907: }
2908: if ($allowed) {
2909: $home=&homeserver($cnum,$cdom);
2910: if ($env{'form.forceedit'}) {
2911: $forceview = 1;
2912: } else {
2913: $forceedit = 1;
2914: }
2915: $cfile = $resurl;
2916: } else {
2917: return;
2918: }
2919: } else {
1.1172.2.15 raeburn 2920: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2921: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2922: return;
2923: }
2924: } elsif (!$crsedit) {
1.1172.2.13 raeburn 2925: #
2926: # No edit allowed where CC has switched to student role.
2927: #
2928: return;
2929: }
2930: }
2931: }
2932:
2933: if ($file ne '') {
2934: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2935: if (&is_course_upload($file,$cnum,$cdom)) {
2936: $uploaded = 1;
2937: $incourse = 1;
2938: if ($file =~/\.(htm|html|css|js|txt)$/) {
2939: $cfile = &hreflocation('',$file);
2940: if ($env{'form.forceedit'}) {
2941: $forceview = 1;
2942: } else {
2943: $forceedit = 1;
2944: }
2945: }
2946: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2947: $incourse = 1;
2948: if ($env{'form.forceedit'}) {
2949: $forceview = 1;
2950: } else {
2951: $forceedit = 1;
2952: }
2953: $cfile = $resurl;
2954: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2955: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2956: $incourse = 1;
2957: if ($env{'form.forceedit'}) {
2958: $forceview = 1;
2959: } else {
2960: $forceedit = 1;
2961: }
2962: $cfile = $resurl;
2963: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2964: $incourse = 1;
2965: $cfile = $resurl.'/smpedit';
2966: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2967: $incourse = 1;
2968: if ($env{'form.forceedit'}) {
2969: $forceview = 1;
2970: } else {
2971: $forceedit = 1;
2972: }
2973: $cfile = $resurl;
1.1172.2.15 raeburn 2974: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2975: $incourse = 1;
2976: if ($env{'form.forceedit'}) {
2977: $forceview = 1;
2978: } else {
2979: $forceedit = 1;
2980: }
2981: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 2982: }
2983: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2984: my $template = '/res/lib/templates/simpleproblem.problem';
2985: if (&is_on_map($template)) {
2986: $incourse = 1;
2987: $forceview = 1;
2988: $cfile = $template;
2989: }
2990: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2991: $incourse = 1;
2992: if ($env{'form.forceedit'}) {
2993: $forceview = 1;
2994: } else {
2995: $forceedit = 1;
2996: }
2997: $cfile = $resurl;
2998: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2999: $incourse = 1;
3000: $forceview = 1;
3001: if ($symb) {
3002: my ($map,$id,$res)=&decode_symb($symb);
3003: $env{'request.symb'} = $symb;
3004: $cfile = &clutter($res);
3005: } else {
3006: $cfile = $env{'form.suppurl'};
3007: $cfile =~ s{^http://}{};
3008: $cfile = '/adm/wrapper/ext/'.$cfile;
3009: }
1.1172.2.31 raeburn 3010: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3011: if ($env{'form.forceedit'}) {
3012: $forceview = 1;
3013: } else {
3014: $forceedit = 1;
3015: }
3016: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3017: }
3018: }
3019: if ($uploaded || $incourse) {
3020: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3021: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3022: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3023: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3024: # Check that the user has permission to edit this resource
3025: my $setpriv = 1;
3026: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3027: if (defined($cfudom)) {
3028: $home=&homeserver($cfuname,$cfudom);
3029: $cfile=$file;
3030: }
3031: }
3032: if (($cfile ne '') && (!$incourse || $uploaded) &&
3033: (($home ne '') && ($home ne 'no_host'))) {
3034: my @ids=¤t_machine_ids();
3035: unless (grep(/^\Q$home\E$/,@ids)) {
3036: $switchserver=1;
3037: }
3038: }
3039: }
3040: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3041: }
3042:
3043: sub is_course_upload {
3044: my ($file,$cnum,$cdom) = @_;
3045: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3046: $uploadpath =~ s{^\/}{};
3047: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3048: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3049: return 1;
3050: }
3051: return;
3052: }
3053:
3054: sub in_course {
3055: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3056: if ($hideprivileged) {
3057: my $skipuser;
1.1172.2.23 raeburn 3058: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3059: my @possdoms = ($cdom);
3060: if ($coursehash{'checkforpriv'}) {
3061: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3062: }
3063: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3064: $skipuser = 1;
3065: if ($coursehash{'nothideprivileged'}) {
3066: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3067: my $user;
3068: if ($item =~ /:/) {
3069: $user = $item;
3070: } else {
3071: $user = join(':',split(/[\@]/,$item));
3072: }
3073: if ($user eq $uname.':'.$udom) {
3074: undef($skipuser);
3075: last;
3076: }
3077: }
3078: }
3079: if ($skipuser) {
3080: return 0;
3081: }
3082: }
3083: }
3084: $type ||= 'any';
3085: if (!defined($cdom) || !defined($cnum)) {
3086: my $cid = $env{'request.course.id'};
3087: $cdom = $env{'course.'.$cid.'.domain'};
3088: $cnum = $env{'course.'.$cid.'.num'};
3089: }
3090: my $typesref;
3091: if (($type eq 'any') || ($type eq 'all')) {
3092: $typesref = ['active','previous','future'];
3093: } elsif ($type eq 'previous' || $type eq 'future') {
3094: $typesref = [$type];
3095: }
3096: my %roles = &get_my_roles($uname,$udom,'userroles',
3097: $typesref,undef,[$cdom]);
3098: my ($tmp) = keys(%roles);
3099: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3100: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3101: if (@course_roles > 0) {
3102: return 1;
3103: }
3104: return 0;
3105: }
3106:
1.478 albertel 3107: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3108: # input: action, courseID, current domain, intended
1.637 raeburn 3109: # path to file, source of file, instruction to parse file for objects,
3110: # ref to hash for embedded objects,
3111: # ref to hash for codebase of java objects.
1.1095 raeburn 3112: # reference to scalar to accommodate mime type determined
3113: # from File::MMagic if $parser = parse.
1.637 raeburn 3114: #
1.485 raeburn 3115: # output: url to file (if action was uploaddoc),
3116: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3117: #
1.478 albertel 3118: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3119: # course.
1.477 raeburn 3120: #
1.478 albertel 3121: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3122: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3123: # course's home server.
1.477 raeburn 3124: #
1.478 albertel 3125: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3126: # be copied from $source (current location) to
3127: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3128: # and will then be copied to
3129: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3130: # course's home server.
1.485 raeburn 3131: #
1.481 raeburn 3132: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3133: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3134: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3135: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3136: # in course's home server.
1.637 raeburn 3137: #
1.477 raeburn 3138:
3139: sub process_coursefile {
1.1095 raeburn 3140: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3141: $mimetype)=@_;
1.477 raeburn 3142: my $fetchresult;
1.638 albertel 3143: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3144: if ($action eq 'propagate') {
1.638 albertel 3145: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3146: $home);
1.481 raeburn 3147: } else {
1.477 raeburn 3148: my $fpath = '';
3149: my $fname = $file;
1.478 albertel 3150: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3151: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3152: my $filepath = &build_filepath($fpath);
1.481 raeburn 3153: if ($action eq 'copy') {
3154: if ($source eq '') {
3155: $fetchresult = 'no source file';
3156: return $fetchresult;
3157: } else {
3158: my $destination = $filepath.'/'.$fname;
3159: rename($source,$destination);
3160: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3161: $home);
1.481 raeburn 3162: }
3163: } elsif ($action eq 'uploaddoc') {
3164: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3165: print $fh $env{'form.'.$source};
1.481 raeburn 3166: close($fh);
1.637 raeburn 3167: if ($parser eq 'parse') {
1.1024 raeburn 3168: my $mm = new File::MMagic;
1.1095 raeburn 3169: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3170: if ($type eq 'text/html') {
1.1024 raeburn 3171: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3172: unless ($parse_result eq 'ok') {
3173: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3174: }
1.637 raeburn 3175: }
1.1095 raeburn 3176: if (ref($mimetype)) {
3177: $$mimetype = $type;
3178: }
1.637 raeburn 3179: }
1.477 raeburn 3180: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3181: $home);
1.481 raeburn 3182: if ($fetchresult eq 'ok') {
3183: return '/uploaded/'.$fpath.'/'.$fname;
3184: } else {
3185: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3186: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3187: return '/adm/notfound.html';
3188: }
1.477 raeburn 3189: }
3190: }
1.485 raeburn 3191: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3192: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3193: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3194: }
3195: return $fetchresult;
3196: }
3197:
1.637 raeburn 3198: sub build_filepath {
3199: my ($fpath) = @_;
3200: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3201: unless ($fpath eq '') {
3202: my @parts=split('/',$fpath);
3203: foreach my $part (@parts) {
3204: $filepath.= '/'.$part;
3205: if ((-e $filepath)!=1) {
3206: mkdir($filepath,0777);
3207: }
3208: }
3209: }
3210: return $filepath;
3211: }
3212:
3213: sub store_edited_file {
1.638 albertel 3214: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3215: my $file = $primary_url;
3216: $file =~ s#^/uploaded/$docudom/$docuname/##;
3217: my $fpath = '';
3218: my $fname = $file;
3219: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3220: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3221: my $filepath = &build_filepath($fpath);
3222: open(my $fh,'>'.$filepath.'/'.$fname);
3223: print $fh $content;
3224: close($fh);
1.638 albertel 3225: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3226: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3227: $home);
1.637 raeburn 3228: if ($$fetchresult eq 'ok') {
3229: return '/uploaded/'.$fpath.'/'.$fname;
3230: } else {
1.638 albertel 3231: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3232: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3233: return '/adm/notfound.html';
3234: }
3235: }
3236:
1.531 albertel 3237: sub clean_filename {
1.831 albertel 3238: my ($fname,$args)=@_;
1.315 www 3239: # Replace Windows backslashes by forward slashes
1.257 www 3240: $fname=~s/\\/\//g;
1.831 albertel 3241: if (!$args->{'keep_path'}) {
3242: # Get rid of everything but the actual filename
3243: $fname=~s/^.*\/([^\/]+)$/$1/;
3244: }
1.315 www 3245: # Replace spaces by underscores
3246: $fname=~s/\s+/\_/g;
3247: # Replace all other weird characters by nothing
1.831 albertel 3248: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3249: # Replace all .\d. sequences with _\d. so they no longer look like version
3250: # numbers
3251: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3252: return $fname;
3253: }
1.1051 raeburn 3254: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3255: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3256: # image with the same aspect ratio as the original, but with dimensions which do
3257: # not exceed $resizewidth and $resizeheight.
3258:
1.984 neumanie 3259: sub resizeImage {
1.1051 raeburn 3260: my ($img_path,$resizewidth,$resizeheight) = @_;
3261: my $ima = Image::Magick->new;
3262: my $resized;
3263: if (-e $img_path) {
3264: $ima->Read($img_path);
3265: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3266: my $width = $ima->Get('width');
3267: my $height = $ima->Get('height');
3268: if ($width > $resizewidth) {
3269: my $factor = $width/$resizewidth;
3270: my $newheight = $height/$factor;
3271: $ima->Scale(width=>$resizewidth,height=>$newheight);
3272: $resized = 1;
3273: }
3274: }
3275: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3276: my $width = $ima->Get('width');
3277: my $height = $ima->Get('height');
3278: if ($height > $resizeheight) {
3279: my $factor = $height/$resizeheight;
3280: my $newwidth = $width/$factor;
3281: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3282: $resized = 1;
3283: }
3284: }
3285: if ($resized) {
3286: $ima->Write($img_path);
3287: }
3288: }
3289: return;
1.977 amueller 3290: }
3291:
1.608 albertel 3292: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3293: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3294: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3295: # $context - possible values: coursedoc, existingfile, overwrite,
3296: # canceloverwrite, or ''.
3297: # if 'coursedoc': upload to the current course
3298: # if 'existingfile': write file to tmp/overwrites directory
3299: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3300: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3301: # $subdir - directory in userfile to store the file into
1.858 raeburn 3302: # $parser - instruction to parse file for objects ($parser = parse)
3303: # $allfiles - reference to hash for embedded objects
3304: # $codebase - reference to hash for codebase of java objects
3305: # $desuname - username for permanent storage of uploaded file
3306: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3307: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3308: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3309: # $resizewidth - width (pixels) to which to resize uploaded image
3310: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3311: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3312: # from File::MMagic.
1.858 raeburn 3313: #
1.686 albertel 3314: # output: url of file in userspace, or error: <message>
3315: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3316:
1.531 albertel 3317: sub userfileupload {
1.1090 raeburn 3318: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3319: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3320: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3321: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3322: $fname=&clean_filename($fname);
1.1090 raeburn 3323: # See if there is anything left
1.257 www 3324: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3325: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3326: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3327: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3328: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3329: my $now = time;
1.1090 raeburn 3330: my $filepath;
1.1095 raeburn 3331: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3332: $filepath = 'tmp/helprequests/'.$now;
3333: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3334: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3335: '_'.$env{'user.domain'}.'/pending';
3336: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3337: my ($docuname,$docudom);
3338: if ($destudom) {
3339: $docudom = $destudom;
3340: } else {
3341: $docudom = $env{'user.domain'};
3342: }
3343: if ($destuname) {
3344: $docuname = $destuname;
3345: } else {
3346: $docuname = $env{'user.name'};
3347: }
3348: if (exists($env{'form.group'})) {
3349: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3350: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3351: }
3352: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3353: if ($context eq 'canceloverwrite') {
3354: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3355: if (-e $tempfile) {
3356: my @info = stat($tempfile);
3357: if ($info[9] eq $env{'form.timestamp'}) {
3358: unlink($tempfile);
3359: }
3360: }
3361: return;
1.523 raeburn 3362: }
3363: }
1.1090 raeburn 3364: # Create the directory if not present
1.741 raeburn 3365: my @parts=split(/\//,$filepath);
3366: my $fullpath = $perlvar{'lonDaemons'};
3367: for (my $i=0;$i<@parts;$i++) {
3368: $fullpath .= '/'.$parts[$i];
3369: if ((-e $fullpath)!=1) {
3370: mkdir($fullpath,0777);
3371: }
3372: }
3373: open(my $fh,'>'.$fullpath.'/'.$fname);
3374: print $fh $env{'form.'.$formname};
3375: close($fh);
1.1090 raeburn 3376: if ($context eq 'existingfile') {
3377: my @info = stat($fullpath.'/'.$fname);
3378: return ($fullpath.'/'.$fname,$info[9]);
3379: } else {
3380: return $fullpath.'/'.$fname;
3381: }
1.523 raeburn 3382: }
1.995 raeburn 3383: if ($subdir eq 'scantron') {
3384: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3385: } else {
1.995 raeburn 3386: $fname="$subdir/$fname";
3387: }
1.1090 raeburn 3388: if ($context eq 'coursedoc') {
1.638 albertel 3389: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3390: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3391: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3392: return &finishuserfileupload($docuname,$docudom,
3393: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3394: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3395: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3396: } else {
1.1172.2.21 raeburn 3397: if ($env{'form.folder'}) {
3398: $fname=$env{'form.folder'}.'/'.$fname;
3399: }
1.638 albertel 3400: return &process_coursefile('uploaddoc',$docuname,$docudom,
3401: $fname,$formname,$parser,
1.1095 raeburn 3402: $allfiles,$codebase,$mimetype);
1.481 raeburn 3403: }
1.719 banghart 3404: } elsif (defined($destuname)) {
3405: my $docuname=$destuname;
3406: my $docudom=$destudom;
1.860 raeburn 3407: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3408: $parser,$allfiles,$codebase,
1.1051 raeburn 3409: $thumbwidth,$thumbheight,
1.1095 raeburn 3410: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3411: } else {
1.638 albertel 3412: my $docuname=$env{'user.name'};
3413: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3414: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3415: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3416: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3417: }
1.860 raeburn 3418: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3419: $parser,$allfiles,$codebase,
1.1051 raeburn 3420: $thumbwidth,$thumbheight,
1.1095 raeburn 3421: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3422: }
1.271 www 3423: }
3424:
3425: sub finishuserfileupload {
1.860 raeburn 3426: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3427: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3428: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3429: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3430:
1.860 raeburn 3431: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3432: $file=$fname;
3433: if ($fname=~m|/|) {
3434: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3435: $path.=$fnamepath.'/';
3436: }
1.259 www 3437: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3438: my $count;
3439: for ($count=4;$count<=$#parts;$count++) {
3440: $filepath.="/$parts[$count]";
3441: if ((-e $filepath)!=1) {
3442: mkdir($filepath,0777);
3443: }
3444: }
1.984 neumanie 3445:
1.258 www 3446: # Save the file
3447: {
1.701 albertel 3448: if (!open(FH,'>'.$filepath.'/'.$file)) {
3449: &logthis('Failed to create '.$filepath.'/'.$file);
3450: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3451: return '/adm/notfound.html';
3452: }
1.1090 raeburn 3453: if ($context eq 'overwrite') {
1.1117 foxr 3454: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3455: my $target = $filepath.'/'.$file;
3456: if (-e $source) {
3457: my @info = stat($source);
3458: if ($info[9] eq $env{'form.timestamp'}) {
3459: unless (&File::Copy::move($source,$target)) {
3460: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3461: return "Moving from $source failed";
3462: }
3463: } else {
3464: return "Temporary file: $source had unexpected date/time for last modification";
3465: }
3466: } else {
3467: return "Temporary file: $source missing";
3468: }
3469: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3470: &logthis('Failed to write to '.$filepath.'/'.$file);
3471: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3472: return '/adm/notfound.html';
3473: }
1.570 albertel 3474: close(FH);
1.1051 raeburn 3475: if ($resizewidth && $resizeheight) {
3476: my $mm = new File::MMagic;
3477: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3478: if ($mime_type =~ m{^image/}) {
3479: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3480: }
1.977 amueller 3481: }
1.258 www 3482: }
1.1152 raeburn 3483: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3484: if (ref($mimetype)) {
3485: if ($$mimetype eq '') {
3486: my $mm = new File::MMagic;
3487: my $type = $mm->checktype_filename($filepath.'/'.$file);
3488: $$mimetype = $type;
3489: }
3490: }
3491: }
1.637 raeburn 3492: if ($parser eq 'parse') {
1.1152 raeburn 3493: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3494: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3495: $allfiles,$codebase);
3496: unless ($parse_result eq 'ok') {
3497: &logthis('Failed to parse '.$filepath.$file.
3498: ' for embedded media: '.$parse_result);
3499: }
1.637 raeburn 3500: }
3501: }
1.860 raeburn 3502: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3503: my $input = $filepath.'/'.$file;
3504: my $output = $filepath.'/'.'tn-'.$file;
3505: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3506: system("convert -sample $thumbsize $input $output");
3507: if (-e $filepath.'/'.'tn-'.$file) {
3508: $fetchthumb = 1;
3509: }
3510: }
1.858 raeburn 3511:
1.259 www 3512: # Notify homeserver to grep it
3513: #
1.984 neumanie 3514: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3515: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3516: if ($fetchresult eq 'ok') {
1.860 raeburn 3517: if ($fetchthumb) {
3518: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3519: if ($thumbresult ne 'ok') {
3520: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3521: $docuhome.': '.$thumbresult);
3522: }
3523: }
1.259 www 3524: #
1.258 www 3525: # Return the URL to it
1.494 albertel 3526: return '/uploaded/'.$path.$file;
1.263 www 3527: } else {
1.494 albertel 3528: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3529: ': '.$fetchresult);
1.263 www 3530: return '/adm/notfound.html';
1.858 raeburn 3531: }
1.493 albertel 3532: }
3533:
1.637 raeburn 3534: sub extract_embedded_items {
1.961 raeburn 3535: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3536: my @state = ();
1.1164 raeburn 3537: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3538: my %javafiles = (
3539: codebase => '',
3540: code => '',
3541: archive => ''
3542: );
3543: my %mediafiles = (
3544: src => '',
3545: movie => '',
3546: );
1.648 raeburn 3547: my $p;
3548: if ($content) {
3549: $p = HTML::LCParser->new($content);
3550: } else {
1.961 raeburn 3551: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3552: }
1.641 albertel 3553: while (my $t=$p->get_token()) {
1.640 albertel 3554: if ($t->[0] eq 'S') {
3555: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3556: push(@state, $tagname);
1.648 raeburn 3557: if (lc($tagname) eq 'allow') {
3558: &add_filetype($allfiles,$attr->{'src'},'src');
3559: }
1.640 albertel 3560: if (lc($tagname) eq 'img') {
3561: &add_filetype($allfiles,$attr->{'src'},'src');
3562: }
1.886 albertel 3563: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 3564: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3565: &add_filetype($allfiles,$attr->{'href'},'href');
3566: }
1.886 albertel 3567: }
1.645 raeburn 3568: if (lc($tagname) eq 'script') {
1.1164 raeburn 3569: my $src;
1.645 raeburn 3570: if ($attr->{'archive'} =~ /\.jar$/i) {
3571: &add_filetype($allfiles,$attr->{'archive'},'archive');
3572: } else {
1.1164 raeburn 3573: if ($attr->{'src'} ne '') {
3574: $src = $attr->{'src'};
3575: &add_filetype($allfiles,$src,'src');
3576: }
3577: }
3578: my $text = $p->get_trimmed_text();
3579: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3580: my @swfargs = split(/,/,$1);
3581: foreach my $item (@swfargs) {
3582: $item =~ s/["']//g;
3583: $item =~ s/^\s+//;
3584: $item =~ s/\s+$//;
3585: }
3586: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3587: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3588: push(@{$related{$swfargs[0]}},$swfargs[2]);
3589: } else {
3590: $related{$swfargs[0]} = [$swfargs[2]];
3591: }
3592: }
1.645 raeburn 3593: }
3594: }
3595: if (lc($tagname) eq 'link') {
3596: if (lc($attr->{'rel'}) eq 'stylesheet') {
3597: &add_filetype($allfiles,$attr->{'href'},'href');
3598: }
3599: }
1.640 albertel 3600: if (lc($tagname) eq 'object' ||
3601: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3602: foreach my $item (keys(%javafiles)) {
3603: $javafiles{$item} = '';
3604: }
1.1164 raeburn 3605: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3606: $lastids{lc($tagname)} = $attr->{'id'};
3607: }
1.640 albertel 3608: }
3609: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3610: my $name = lc($attr->{'name'});
3611: foreach my $item (keys(%javafiles)) {
3612: if ($name eq $item) {
3613: $javafiles{$item} = $attr->{'value'};
3614: last;
3615: }
3616: }
1.1164 raeburn 3617: my $pathfrom;
1.640 albertel 3618: foreach my $item (keys(%mediafiles)) {
3619: if ($name eq $item) {
1.1164 raeburn 3620: $pathfrom = $attr->{'value'};
3621: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3622: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3623: last;
3624: }
3625: }
1.1164 raeburn 3626: if ($name eq 'flashvars') {
3627: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3628: }
3629: if ($pathfrom ne '') {
3630: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3631: $pathfrom);
3632: }
1.640 albertel 3633: }
3634: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3635: foreach my $item (keys(%javafiles)) {
3636: if ($attr->{$item}) {
3637: $javafiles{$item} = $attr->{$item};
3638: last;
3639: }
3640: }
3641: foreach my $item (keys(%mediafiles)) {
3642: if ($attr->{$item}) {
3643: &add_filetype($allfiles,$attr->{$item},$item);
3644: last;
3645: }
3646: }
1.1164 raeburn 3647: if (lc($tagname) eq 'embed') {
3648: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3649: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3650: $attr->{'src'});
3651: }
3652: }
1.640 albertel 3653: }
1.1172.2.35 raeburn 3654: if (lc($tagname) eq 'iframe') {
3655: my $src = $attr->{'src'} ;
3656: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3657: &add_filetype($allfiles,$src,'src');
3658: } elsif ($src =~ m{^/}) {
3659: if ($env{'request.course.id'}) {
3660: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3661: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3662: my $url = &hreflocation('',$fullpath);
3663: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3664: my $relpath = $1;
3665: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3666: &add_filetype($allfiles,$1,'src');
3667: }
3668: }
3669: }
3670: }
3671: }
1.1164 raeburn 3672: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 3673: pop(@state);
1.1164 raeburn 3674: }
1.640 albertel 3675: } elsif ($t->[0] eq 'E') {
3676: my ($tagname) = ($t->[1]);
3677: if ($javafiles{'codebase'} ne '') {
3678: $javafiles{'codebase'} .= '/';
3679: }
3680: if (lc($tagname) eq 'applet' ||
3681: lc($tagname) eq 'object' ||
3682: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3683: ) {
3684: foreach my $item (keys(%javafiles)) {
3685: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3686: my $file=$javafiles{'codebase'}.$javafiles{$item};
3687: &add_filetype($allfiles,$file,$item);
3688: }
3689: }
3690: }
3691: pop @state;
3692: }
3693: }
1.1164 raeburn 3694: foreach my $id (sort(keys(%flashvars))) {
3695: if ($shockwave{$id} ne '') {
3696: my @pairs = split(/\&/,$flashvars{$id});
3697: foreach my $pair (@pairs) {
3698: my ($key,$value) = split(/\=/,$pair);
3699: if ($key eq 'thumb') {
3700: &add_filetype($allfiles,$value,$key);
3701: } elsif ($key eq 'content') {
3702: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3703: my ($ext) = ($value =~ /\.([^.]+)$/);
3704: if ($ext ne '') {
3705: &add_filetype($allfiles,$path.$value,$ext);
3706: }
3707: }
3708: }
3709: }
3710: }
1.637 raeburn 3711: return 'ok';
3712: }
3713:
1.639 albertel 3714: sub add_filetype {
3715: my ($allfiles,$file,$type)=@_;
3716: if (exists($allfiles->{$file})) {
3717: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3718: push(@{$allfiles->{$file}}, &escape($type));
3719: }
3720: } else {
3721: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3722: }
3723: }
3724:
1.1164 raeburn 3725: sub embedded_dependency {
3726: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3727: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3728: if (($identifier ne '') &&
3729: (ref($related->{$identifier}) eq 'ARRAY') &&
3730: ($pathfrom ne '')) {
3731: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3732: foreach my $dep (@{$related->{$identifier}}) {
3733: &add_filetype($allfiles,$path.$dep,'object');
3734: }
3735: }
3736: }
3737: return;
3738: }
3739:
1.493 albertel 3740: sub removeuploadedurl {
1.984 neumanie 3741: my ($url)=@_;
3742: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3743: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3744: }
3745:
3746: sub removeuserfile {
3747: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3748: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3749: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3750: if ($result eq 'ok') {
1.798 raeburn 3751: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3752: my $metafile = $fname.'.meta';
3753: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3754: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3755: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3756: my $sqlresult =
1.823 albertel 3757: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3758: 'portfolio_metadata',$group,
3759: 'delete');
1.798 raeburn 3760: }
3761: }
3762: return $result;
1.257 www 3763: }
1.15 www 3764:
1.530 albertel 3765: sub mkdiruserfile {
3766: my ($docuname,$docudom,$dir)=@_;
3767: my $home=&homeserver($docuname,$docudom);
3768: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3769: }
3770:
1.531 albertel 3771: sub renameuserfile {
3772: my ($docuname,$docudom,$old,$new)=@_;
3773: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3774: my $result = &reply("renameuserfile:$docudom:$docuname:".
3775: &escape("$old").':'.&escape("$new"),$home);
3776: if ($result eq 'ok') {
3777: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3778: my $oldmeta = $old.'.meta';
3779: my $newmeta = $new.'.meta';
3780: my $metaresult =
3781: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3782: my $url = "/uploaded/$docudom/$docuname/$old";
3783: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3784: my $sqlresult =
1.823 albertel 3785: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3786: 'portfolio_metadata',$group,
3787: 'delete');
1.798 raeburn 3788: }
3789: }
3790: return $result;
1.531 albertel 3791: }
3792:
1.14 www 3793: # ------------------------------------------------------------------------- Log
3794:
3795: sub log {
3796: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3797: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3798: }
3799:
3800: # ------------------------------------------------------------------ Course Log
1.352 www 3801: #
3802: # This routine flushes several buffers of non-mission-critical nature
3803: #
1.157 www 3804:
3805: sub flushcourselogs {
1.352 www 3806: &logthis('Flushing log buffers');
3807: #
3808: # course logs
3809: # This is a log of all transactions in a course, which can be used
3810: # for data mining purposes
3811: #
3812: # It also collects the courseid database, which lists last transaction
3813: # times and course titles for all courseids
3814: #
3815: my %courseidbuffer=();
1.921 raeburn 3816: foreach my $crsid (keys(%courselogs)) {
1.352 www 3817: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3818: &escape($courselogs{$crsid}),
3819: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3820: delete $courselogs{$crsid};
3821: } else {
3822: &logthis('Failed to flush log buffer for '.$crsid);
3823: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3824: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3825: " exceeded maximum size, deleting.</font>");
3826: delete $courselogs{$crsid};
3827: }
1.352 www 3828: }
1.920 raeburn 3829: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3830: 'description' => $coursedescrbuf{$crsid},
3831: 'inst_code' => $courseinstcodebuf{$crsid},
3832: 'type' => $coursetypebuf{$crsid},
3833: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3834: };
1.191 harris41 3835: }
1.352 www 3836: #
3837: # Write course id database (reverse lookup) to homeserver of courses
3838: # Is used in pickcourse
3839: #
1.840 albertel 3840: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3841: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3842: $courseidbuffer{$crs_home},
3843: $crs_home,'timeonly');
1.352 www 3844: }
3845: #
3846: # File accesses
3847: # Writes to the dynamic metadata of resources to get hit counts, etc.
3848: #
1.449 matthew 3849: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3850: if ($entry =~ /___count$/) {
3851: my ($dom,$name);
1.807 albertel 3852: ($dom,$name,undef)=
1.811 albertel 3853: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3854: if (! defined($dom) || $dom eq '' ||
3855: ! defined($name) || $name eq '') {
1.620 albertel 3856: my $cid = $env{'request.course.id'};
3857: $dom = $env{'request.'.$cid.'.domain'};
3858: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3859: }
1.450 matthew 3860: my $value = $accesshash{$entry};
3861: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3862: my %temphash=($url => $value);
1.449 matthew 3863: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3864: if ($result eq 'ok') {
3865: delete $accesshash{$entry};
3866: }
3867: } else {
1.811 albertel 3868: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3869: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3870: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3871: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3872: delete $accesshash{$entry};
3873: }
1.185 www 3874: }
1.191 harris41 3875: }
1.352 www 3876: #
3877: # Roles
3878: # Reverse lookup of user roles for course faculty/staff and co-authorship
3879: #
1.800 albertel 3880: foreach my $entry (keys(%userrolehash)) {
1.351 www 3881: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3882: split(/\:/,$entry);
3883: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3884: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3885: $rudom,$runame) eq 'ok') {
3886: delete $userrolehash{$entry};
3887: }
3888: }
1.662 raeburn 3889: #
3890: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3891: #
3892: my %domrolebuffer = ();
1.1000 raeburn 3893: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3894: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3895: if ($domrolebuffer{$rudom}) {
3896: $domrolebuffer{$rudom}.='&'.&escape($entry).
3897: '='.&escape($domainrolehash{$entry});
3898: } else {
3899: $domrolebuffer{$rudom}.=&escape($entry).
3900: '='.&escape($domainrolehash{$entry});
3901: }
3902: delete $domainrolehash{$entry};
3903: }
3904: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3905: my %servers = &get_servers($dom,'library');
3906: foreach my $tryserver (keys(%servers)) {
3907: unless (&reply('domroleput:'.$dom.':'.
3908: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3909: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3910: }
1.662 raeburn 3911: }
3912: }
1.186 www 3913: $dumpcount++;
1.157 www 3914: }
3915:
3916: sub courselog {
3917: my $what=shift;
1.158 www 3918: $what=time.':'.$what;
1.620 albertel 3919: unless ($env{'request.course.id'}) { return ''; }
3920: $coursedombuf{$env{'request.course.id'}}=
3921: $env{'course.'.$env{'request.course.id'}.'.domain'};
3922: $coursenumbuf{$env{'request.course.id'}}=
3923: $env{'course.'.$env{'request.course.id'}.'.num'};
3924: $coursehombuf{$env{'request.course.id'}}=
3925: $env{'course.'.$env{'request.course.id'}.'.home'};
3926: $coursedescrbuf{$env{'request.course.id'}}=
3927: $env{'course.'.$env{'request.course.id'}.'.description'};
3928: $courseinstcodebuf{$env{'request.course.id'}}=
3929: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3930: $courseownerbuf{$env{'request.course.id'}}=
3931: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3932: $coursetypebuf{$env{'request.course.id'}}=
3933: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3934: if (defined $courselogs{$env{'request.course.id'}}) {
3935: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3936: } else {
1.620 albertel 3937: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3938: }
1.620 albertel 3939: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3940: &flushcourselogs();
3941: }
1.158 www 3942: }
3943:
3944: sub courseacclog {
3945: my $fnsymb=shift;
1.620 albertel 3946: unless ($env{'request.course.id'}) { return ''; }
3947: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3948: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3949: $what.=':POST';
1.583 matthew 3950: # FIXME: Probably ought to escape things....
1.800 albertel 3951: foreach my $key (keys(%env)) {
3952: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3953: my $formitem = $1;
3954: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3955: $what.=':'.$formitem.'='.$env{$key};
3956: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3957: $what.=':'.$formitem.'='.$env{$key};
3958: }
1.158 www 3959: }
1.191 harris41 3960: }
1.583 matthew 3961: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3962: # FIXME: We should not be depending on a form parameter that someone
3963: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3964: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3965: $what.= ':POST';
3966: # FIXME: Probably ought to escape things....
3967: foreach my $element ('courseexp','crsfulltext','crsrelated',
3968: 'crsdiscuss') {
1.620 albertel 3969: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3970: }
3971: }
1.158 www 3972: }
3973: &courselog($what);
1.149 www 3974: }
3975:
1.185 www 3976: sub countacc {
3977: my $url=&declutter(shift);
1.458 matthew 3978: return if (! defined($url) || $url eq '');
1.620 albertel 3979: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3980: #
3981: # Mark that this url was used in this course
3982: #
1.620 albertel 3983: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3984: #
3985: # Increase the access count for this resource in this child process
3986: #
1.281 www 3987: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3988: $accesshash{$key}++;
1.185 www 3989: }
1.349 www 3990:
1.361 www 3991: sub linklog {
3992: my ($from,$to)=@_;
3993: $from=&declutter($from);
3994: $to=&declutter($to);
3995: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3996: $accesshash{$to.'___'.$from.'___goto'}=1;
3997: }
1.1160 www 3998:
3999: sub statslog {
4000: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4001: if ($users<2) { return; }
4002: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4003: 'course' => $env{'request.course.id'},
4004: 'sections' => '"all"',
4005: 'num_students' => $users,
4006: 'part' => $part,
4007: 'symb' => $symb,
4008: 'mean_tries' => $av_attempts,
4009: 'deg_of_diff' => $degdiff});
4010: foreach my $key (keys(%dynstore)) {
4011: $accesshash{$key}=$dynstore{$key};
4012: }
4013: }
1.361 www 4014:
1.349 www 4015: sub userrolelog {
4016: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4017: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4018: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4019: $userrolehash
4020: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4021: =$tend.':'.$tstart;
1.662 raeburn 4022: }
1.1169 droeschl 4023: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4024: $userrolehash
4025: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4026: =$tend.':'.$tstart;
4027: }
1.1169 droeschl 4028: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 4029: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4030: $domainrolehash
4031: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4032: = $tend.':'.$tstart;
4033: }
1.351 www 4034: }
4035:
1.957 raeburn 4036: sub courserolelog {
4037: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4038: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4039: my $cdom = $1;
4040: my $cnum = $2;
4041: my $sec = $3;
4042: my $namespace = 'rolelog';
4043: my %storehash = (
4044: role => $trole,
4045: start => $tstart,
4046: end => $tend,
4047: selfenroll => $selfenroll,
4048: context => $context,
4049: );
4050: if ($trole eq 'gr') {
4051: $namespace = 'groupslog';
4052: $storehash{'group'} = $sec;
4053: } else {
4054: $storehash{'section'} = $sec;
4055: }
4056: &write_log('course',$namespace,\%storehash,$delflag,$username,
4057: $domain,$cnum,$cdom);
4058: if (($trole ne 'st') || ($sec ne '')) {
4059: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4060: }
4061: }
4062: return;
4063: }
4064:
1.1172.2.9 raeburn 4065: sub domainrolelog {
4066: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4067: if ($area =~ m{^/($match_domain)/$}) {
4068: my $cdom = $1;
4069: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4070: my $namespace = 'rolelog';
4071: my %storehash = (
4072: role => $trole,
4073: start => $tstart,
4074: end => $tend,
4075: context => $context,
4076: );
4077: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4078: $domain,$domconfiguser,$cdom);
4079: }
4080: return;
4081:
4082: }
4083:
4084: sub coauthorrolelog {
4085: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4086: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4087: my $audom = $1;
4088: my $auname = $2;
4089: my $namespace = 'rolelog';
4090: my %storehash = (
4091: role => $trole,
4092: start => $tstart,
4093: end => $tend,
4094: context => $context,
4095: );
4096: &write_log('author',$namespace,\%storehash,$delflag,$username,
4097: $domain,$auname,$audom);
4098: }
4099: return;
4100: }
4101:
1.351 www 4102: sub get_course_adv_roles {
1.948 raeburn 4103: my ($cid,$codes) = @_;
1.620 albertel 4104: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4105: my %coursehash=&coursedescription($cid);
1.988 raeburn 4106: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4107: my %nothide=();
1.800 albertel 4108: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4109: if ($user !~ /:/) {
4110: $nothide{join(':',split(/[\@]/,$user))}=1;
4111: } else {
4112: $nothide{$user}=1;
4113: }
1.470 www 4114: }
1.1172.2.23 raeburn 4115: my @possdoms = ($coursehash{'domain'});
4116: if ($coursehash{'checkforpriv'}) {
4117: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4118: }
1.351 www 4119: my %returnhash=();
4120: my %dumphash=
4121: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4122: my $now=time;
1.997 raeburn 4123: my %privileged;
1.1000 raeburn 4124: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4125: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4126: if (($tstart) && ($tstart<0)) { next; }
4127: if (($tend) && ($tend<$now)) { next; }
4128: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4129: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4130: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4131: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4132: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4133: if ($role eq 'cr') { next; }
1.948 raeburn 4134: if ($codes) {
4135: if ($section) { $role .= ':'.$section; }
4136: if ($returnhash{$role}) {
4137: $returnhash{$role}.=','.$username.':'.$domain;
4138: } else {
4139: $returnhash{$role}=$username.':'.$domain;
4140: }
1.351 www 4141: } else {
1.988 raeburn 4142: my $key=&plaintext($role,$crstype);
1.973 bisitz 4143: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4144: if ($returnhash{$key}) {
4145: $returnhash{$key}.=','.$username.':'.$domain;
4146: } else {
4147: $returnhash{$key}=$username.':'.$domain;
4148: }
1.351 www 4149: }
1.948 raeburn 4150: }
1.400 www 4151: return %returnhash;
4152: }
4153:
4154: sub get_my_roles {
1.937 raeburn 4155: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4156: unless (defined($uname)) { $uname=$env{'user.name'}; }
4157: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4158: my (%dumphash,%nothide);
1.1086 raeburn 4159: if ($context eq 'userroles') {
1.1166 raeburn 4160: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4161: } else {
1.1172.2.23 raeburn 4162: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4163: if ($hidepriv) {
4164: my %coursehash=&coursedescription($udom.'_'.$uname);
4165: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4166: if ($user !~ /:/) {
4167: $nothide{join(':',split(/[\@]/,$user))} = 1;
4168: } else {
4169: $nothide{$user} = 1;
4170: }
4171: }
4172: }
1.858 raeburn 4173: }
1.400 www 4174: my %returnhash=();
4175: my $now=time;
1.999 raeburn 4176: my %privileged;
1.800 albertel 4177: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4178: my ($role,$tend,$tstart);
4179: if ($context eq 'userroles') {
1.1149 raeburn 4180: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4181: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4182: } else {
4183: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4184: }
1.400 www 4185: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4186: my $status = 'active';
1.939 raeburn 4187: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4188: $status = 'previous';
4189: }
4190: if (($tstart) && ($now<$tstart)) {
4191: $status = 'future';
4192: }
4193: if (ref($types) eq 'ARRAY') {
4194: if (!grep(/^\Q$status\E$/,@{$types})) {
4195: next;
4196: }
4197: } else {
4198: if ($status ne 'active') {
4199: next;
4200: }
4201: }
1.867 raeburn 4202: my ($rolecode,$username,$domain,$section,$area);
4203: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4204: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4205: (undef,$domain,$username,$section) = split(/\//,$area);
4206: } else {
4207: ($role,$username,$domain,$section) = split(/\:/,$entry);
4208: }
1.832 raeburn 4209: if (ref($roledoms) eq 'ARRAY') {
4210: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4211: next;
4212: }
4213: }
4214: if (ref($roles) eq 'ARRAY') {
4215: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4216: if ($role =~ /^cr\//) {
4217: if (!grep(/^cr$/,@{$roles})) {
4218: next;
4219: }
1.1104 raeburn 4220: } elsif ($role =~ /^gr\//) {
4221: if (!grep(/^gr$/,@{$roles})) {
4222: next;
4223: }
1.922 raeburn 4224: } else {
4225: next;
4226: }
1.832 raeburn 4227: }
1.867 raeburn 4228: }
1.937 raeburn 4229: if ($hidepriv) {
1.1172.2.23 raeburn 4230: my @privroles = ('dc','su');
1.999 raeburn 4231: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4232: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4233: } else {
1.1172.2.23 raeburn 4234: my $possdoms = [$domain];
4235: if (ref($roledoms) eq 'ARRAY') {
4236: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4237: }
1.1172.2.23 raeburn 4238: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4239: if (!$nothide{$username.':'.$domain}) {
4240: next;
4241: }
4242: }
1.937 raeburn 4243: }
4244: }
1.933 raeburn 4245: if ($withsec) {
4246: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4247: $tstart.':'.$tend;
4248: } else {
4249: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4250: }
1.832 raeburn 4251: }
1.373 www 4252: return %returnhash;
1.399 www 4253: }
4254:
4255: # ----------------------------------------------------- Frontpage Announcements
4256: #
4257: #
4258:
4259: sub postannounce {
4260: my ($server,$text)=@_;
1.844 albertel 4261: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4262: unless ($text=~/\w/) { $text=''; }
4263: return &reply('setannounce:'.&escape($text),$server);
4264: }
4265:
4266: sub getannounce {
1.448 albertel 4267:
4268: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4269: my $announcement='';
1.800 albertel 4270: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4271: close($fh);
1.399 www 4272: if ($announcement=~/\w/) {
4273: return
4274: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4275: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4276: } else {
4277: return '';
4278: }
4279: } else {
4280: return '';
4281: }
1.351 www 4282: }
1.353 www 4283:
4284: # ---------------------------------------------------------- Course ID routines
4285: # Deal with domain's nohist_courseid.db files
4286: #
4287:
4288: sub courseidput {
1.921 raeburn 4289: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4290: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4291: my $outcome;
4292: if ($caller eq 'timeonly') {
4293: my $cids = '';
4294: foreach my $item (keys(%$storehash)) {
4295: $cids.=&escape($item).'&';
4296: }
4297: $cids=~s/\&$//;
4298: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4299: $coursehome);
4300: } else {
4301: my $items = '';
4302: foreach my $item (keys(%$storehash)) {
4303: $items.= &escape($item).'='.
4304: &freeze_escape($$storehash{$item}).'&';
4305: }
4306: $items=~s/\&$//;
4307: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4308: $coursehome);
1.918 raeburn 4309: }
4310: if ($outcome eq 'unknown_cmd') {
4311: my $what;
4312: foreach my $cid (keys(%$storehash)) {
4313: $what .= &escape($cid).'=';
1.921 raeburn 4314: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4315: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4316: }
4317: $what =~ s/\:$/&/;
4318: }
4319: $what =~ s/\&$//;
4320: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4321: } else {
4322: return $outcome;
4323: }
1.353 www 4324: }
4325:
4326: sub courseiddump {
1.921 raeburn 4327: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4328: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4329: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 4330: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 4331: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4332: my $as_hash = 1;
4333: my %returnhash;
4334: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4335: my %libserv = &all_library();
4336: foreach my $tryserver (keys(%libserv)) {
4337: if ( ( $hostidflag == 1
4338: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4339: || (!defined($hostidflag)) ) {
4340:
1.918 raeburn 4341: if (($domfilter eq '') ||
4342: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 4343: my $rep;
4344: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
4345: $rep = &LONCAPA::Lond::dump_course_id_handler(
4346: join(":", (&host_domain($tryserver), $sincefilter,
4347: &escape($descfilter), &escape($instcodefilter),
4348: &escape($ownerfilter), &escape($coursefilter),
4349: &escape($typefilter), &escape($regexp_ok),
4350: $as_hash, &escape($selfenrollonly),
4351: &escape($catfilter), $showhidden, $caller,
4352: &escape($cloner), &escape($cc_clone), $cloneonly,
4353: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 4354: &escape($creationcontext),$domcloner,$hasuniquecode,
4355: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 4356: } else {
4357: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4358: $sincefilter.':'.&escape($descfilter).':'.
4359: &escape($instcodefilter).':'.&escape($ownerfilter).
4360: ':'.&escape($coursefilter).':'.&escape($typefilter).
4361: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4362: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4363: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4364: &escape($cc_clone).':'.$cloneonly.':'.
4365: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 4366: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4367: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 4368: }
4369:
1.918 raeburn 4370: my @pairs=split(/\&/,$rep);
4371: foreach my $item (@pairs) {
4372: my ($key,$value)=split(/\=/,$item,2);
4373: $key = &unescape($key);
4374: next if ($key =~ /^error: 2 /);
4375: my $result = &thaw_unescape($value);
4376: if (ref($result) eq 'HASH') {
4377: $returnhash{$key}=$result;
4378: } else {
1.921 raeburn 4379: my @responses = split(/:/,$value);
4380: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4381: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4382: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4383: }
1.1008 raeburn 4384: }
1.353 www 4385: }
4386: }
4387: }
4388: }
4389: return %returnhash;
4390: }
4391:
1.1055 raeburn 4392: sub courselastaccess {
4393: my ($cdom,$cnum,$hostidref) = @_;
4394: my %returnhash;
4395: if ($cdom && $cnum) {
4396: my $chome = &homeserver($cnum,$cdom);
4397: if ($chome ne 'no_host') {
4398: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4399: &extract_lastaccess(\%returnhash,$rep);
4400: }
4401: } else {
4402: if (!$cdom) { $cdom=''; }
4403: my %libserv = &all_library();
4404: foreach my $tryserver (keys(%libserv)) {
4405: if (ref($hostidref) eq 'ARRAY') {
4406: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4407: }
4408: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4409: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4410: &extract_lastaccess(\%returnhash,$rep);
4411: }
4412: }
4413: }
4414: return %returnhash;
4415: }
4416:
4417: sub extract_lastaccess {
4418: my ($returnhash,$rep) = @_;
4419: if (ref($returnhash) eq 'HASH') {
4420: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4421: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4422: $rep eq '') {
4423: my @pairs=split(/\&/,$rep);
4424: foreach my $item (@pairs) {
4425: my ($key,$value)=split(/\=/,$item,2);
4426: $key = &unescape($key);
4427: next if ($key =~ /^error: 2 /);
4428: $returnhash->{$key} = &thaw_unescape($value);
4429: }
4430: }
4431: }
4432: return;
4433: }
4434:
1.658 raeburn 4435: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4436:
4437: sub dcmailput {
1.685 raeburn 4438: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4439: my $status = &Apache::lonnet::critical(
1.740 www 4440: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4441: &escape($message),$server);
1.662 raeburn 4442: return $status;
4443: }
4444:
1.658 raeburn 4445: sub dcmaildump {
4446: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4447: my %returnhash=();
1.846 albertel 4448:
4449: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4450: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4451: &escape($enddate).':';
4452: my @esc_senders=map { &escape($_)} @$senders;
4453: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4454: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4455: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4456: if (($key) && ($value)) {
4457: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4458: }
4459: }
4460: }
4461: return %returnhash;
4462: }
1.662 raeburn 4463: # ---------------------------------------------------------- Domain roles
4464:
4465: sub get_domain_roles {
4466: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4467: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4468: $startdate = '.';
4469: }
1.1018 raeburn 4470: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4471: $enddate = '.';
4472: }
1.922 raeburn 4473: my $rolelist;
4474: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 4475: $rolelist = join('&',@{$roles});
1.922 raeburn 4476: }
1.662 raeburn 4477: my %personnel = ();
1.841 albertel 4478:
4479: my %servers = &get_servers($dom,'library');
4480: foreach my $tryserver (keys(%servers)) {
4481: %{$personnel{$tryserver}}=();
4482: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4483: &escape($startdate).':'.
4484: &escape($enddate).':'.
4485: &escape($rolelist), $tryserver))) {
4486: my ($key,$value) = split(/\=/,$line,2);
4487: if (($key) && ($value)) {
4488: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4489: }
4490: }
1.662 raeburn 4491: }
4492: return %personnel;
4493: }
1.658 raeburn 4494:
1.1057 www 4495: # ----------------------------------------------------------- Interval timing
1.149 www 4496:
1.1153 www 4497: {
4498: # Caches needed for speedup of navmaps
4499: # We don't want to cache this for very long at all (5 seconds at most)
4500: #
4501: # The user for whom we cache
4502: my $cachedkey='';
4503: # The cached times for this user
4504: my %cachedtimes=();
4505: # When this was last done
1.1172.2.66 raeburn 4506: my $cachedtime='';
1.1153 www 4507:
4508: sub load_all_first_access {
1.1154 raeburn 4509: my ($uname,$udom)=@_;
1.1156 www 4510: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 4511: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4512: return;
4513: }
4514: $cachedtime=time;
4515: $cachedkey=$uname.':'.$udom;
4516: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4517: }
4518:
1.504 albertel 4519: sub get_first_access {
1.1162 raeburn 4520: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4521: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4522: if ($argsymb) { $symb=$argsymb; }
4523: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4524: if ($argmap) { $map = $argmap; }
1.926 albertel 4525: if ($type eq 'course') {
4526: $res='course';
4527: } elsif ($type eq 'map') {
1.588 albertel 4528: $res=&symbread($map);
4529: } else {
4530: $res=$symb;
4531: }
1.1153 www 4532: &load_all_first_access($uname,$udom);
4533: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4534: }
4535:
4536: sub set_first_access {
1.1162 raeburn 4537: my ($type,$interval)=@_;
1.790 albertel 4538: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4539: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4540: if ($type eq 'course') {
4541: $res='course';
4542: } elsif ($type eq 'map') {
1.588 albertel 4543: $res=&symbread($map);
4544: } else {
4545: $res=$symb;
4546: }
1.1153 www 4547: $cachedkey='';
1.1162 raeburn 4548: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4549: if (!$firstaccess) {
1.1162 raeburn 4550: my $start = time;
4551: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4552: $udom,$uname);
4553: if ($putres eq 'ok') {
4554: &put('timerinterval',{"$courseid\0$res"=>$interval},
4555: $udom,$uname);
4556: &appenv(
4557: {
4558: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4559: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4560: }
4561: );
4562: }
4563: return $putres;
1.505 albertel 4564: }
4565: return 'already_set';
1.504 albertel 4566: }
1.1153 www 4567: }
1.1172.2.32 raeburn 4568:
4569: sub checkout {
4570: my ($symb,$tuname,$tudom,$tcrsid)=@_;
4571: my $now=time;
4572: my $lonhost=$perlvar{'lonHostID'};
4573: my $infostr=&escape(
4574: 'CHECKOUTTOKEN&'.
4575: $tuname.'&'.
4576: $tudom.'&'.
4577: $tcrsid.'&'.
4578: $symb.'&'.
4579: $now.'&'.$ENV{'REMOTE_ADDR'});
4580: my $token=&reply('tmpput:'.$infostr,$lonhost);
4581: if ($token=~/^error\:/) {
4582: &logthis("<font color=\"blue\">WARNING: ".
4583: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
4584: "</font>");
4585: return '';
4586: }
4587:
4588: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
4589: $token=~tr/a-z/A-Z/;
4590:
4591: my %infohash=('resource.0.outtoken' => $token,
4592: 'resource.0.checkouttime' => $now,
4593: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
4594:
4595: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4596: return '';
4597: } else {
4598: &logthis("<font color=\"blue\">WARNING: ".
4599: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
4600: "</font>");
4601: }
4602:
4603: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4604: &escape('Checkout '.$infostr.' - '.
4605: $token)) ne 'ok') {
4606: return '';
4607: } else {
4608: &logthis("<font color=\"blue\">WARNING: ".
4609: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
4610: "</font>");
4611: }
4612: return $token;
4613: }
4614:
4615: # ------------------------------------------------------------ Check in an item
4616:
4617: sub checkin {
4618: my $token=shift;
4619: my $now=time;
4620: my ($ta,$tb,$lonhost)=split(/\*/,$token);
4621: $lonhost=~tr/A-Z/a-z/;
4622: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
4623: $dtoken=~s/\W/\_/g;
4624: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
4625: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
4626:
4627: unless (($tuname) && ($tudom)) {
4628: &logthis('Check in '.$token.' ('.$dtoken.') failed');
4629: return '';
4630: }
4631:
4632: unless (&allowed('mgr',$tcrsid)) {
4633: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
4634: $env{'user.name'}.' - '.$env{'user.domain'});
4635: return '';
4636: }
4637:
4638: my %infohash=('resource.0.intoken' => $token,
4639: 'resource.0.checkintime' => $now,
4640: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
4641:
4642: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
4643: return '';
4644: }
4645:
4646: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
4647: &escape('Checkin - '.$token)) ne 'ok') {
4648: return '';
4649: }
4650:
4651: return ($symb,$tuname,$tudom,$tcrsid);
4652: }
4653:
1.110 www 4654: # --------------------------------------------- Set Expire Date for Spreadsheet
4655:
4656: sub expirespread {
4657: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4658: my $cid=$env{'request.course.id'};
1.110 www 4659: if ($cid) {
4660: my $now=time;
4661: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4662: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4663: $env{'course.'.$cid.'.num'}.
1.110 www 4664: ':nohist_expirationdates:'.
4665: &escape($key).'='.$now,
1.620 albertel 4666: $env{'course.'.$cid.'.home'})
1.110 www 4667: }
4668: return 'ok';
1.14 www 4669: }
4670:
1.109 www 4671: # ----------------------------------------------------- Devalidate Spreadsheets
4672:
4673: sub devalidate {
1.325 www 4674: my ($symb,$uname,$udom)=@_;
1.620 albertel 4675: my $cid=$env{'request.course.id'};
1.109 www 4676: if ($cid) {
1.391 matthew 4677: # delete the stored spreadsheets for
4678: # - the student level sheet of this user in course's homespace
4679: # - the assessment level sheet for this resource
4680: # for this user in user's homespace
1.553 albertel 4681: # - current conditional state info
1.325 www 4682: my $key=$uname.':'.$udom.':';
1.109 www 4683: my $status=
1.299 matthew 4684: &del('nohist_calculatedsheets',
1.391 matthew 4685: [$key.'studentcalc:'],
1.620 albertel 4686: $env{'course.'.$cid.'.domain'},
4687: $env{'course.'.$cid.'.num'})
1.133 albertel 4688: .' '.
4689: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4690: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4691: unless ($status eq 'ok ok') {
4692: &logthis('Could not devalidate spreadsheet '.
1.325 www 4693: $uname.' at '.$udom.' for '.
1.109 www 4694: $symb.': '.$status);
1.133 albertel 4695: }
1.553 albertel 4696: &delenv('user.state.'.$cid);
1.109 www 4697: }
4698: }
4699:
1.265 albertel 4700: sub get_scalar {
4701: my ($string,$end) = @_;
4702: my $value;
4703: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4704: $value = $1;
4705: } elsif ($$string =~ s/^([^&]*?)&//) {
4706: $value = $1;
4707: }
4708: return &unescape($value);
4709: }
4710:
4711: sub array2str {
4712: my (@array) = @_;
4713: my $result=&arrayref2str(\@array);
4714: $result=~s/^__ARRAY_REF__//;
4715: $result=~s/__END_ARRAY_REF__$//;
4716: return $result;
4717: }
4718:
1.204 albertel 4719: sub arrayref2str {
4720: my ($arrayref) = @_;
1.265 albertel 4721: my $result='__ARRAY_REF__';
1.204 albertel 4722: foreach my $elem (@$arrayref) {
1.265 albertel 4723: if(ref($elem) eq 'ARRAY') {
4724: $result.=&arrayref2str($elem).'&';
4725: } elsif(ref($elem) eq 'HASH') {
4726: $result.=&hashref2str($elem).'&';
4727: } elsif(ref($elem)) {
4728: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4729: } else {
4730: $result.=&escape($elem).'&';
4731: }
4732: }
4733: $result=~s/\&$//;
1.265 albertel 4734: $result .= '__END_ARRAY_REF__';
1.204 albertel 4735: return $result;
4736: }
4737:
1.168 albertel 4738: sub hash2str {
1.204 albertel 4739: my (%hash) = @_;
4740: my $result=&hashref2str(\%hash);
1.265 albertel 4741: $result=~s/^__HASH_REF__//;
4742: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4743: return $result;
4744: }
4745:
4746: sub hashref2str {
4747: my ($hashref)=@_;
1.265 albertel 4748: my $result='__HASH_REF__';
1.800 albertel 4749: foreach my $key (sort(keys(%$hashref))) {
4750: if (ref($key) eq 'ARRAY') {
4751: $result.=&arrayref2str($key).'=';
4752: } elsif (ref($key) eq 'HASH') {
4753: $result.=&hashref2str($key).'=';
4754: } elsif (ref($key)) {
1.265 albertel 4755: $result.='=';
1.800 albertel 4756: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4757: } else {
1.1132 raeburn 4758: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4759: }
4760:
1.800 albertel 4761: if(ref($hashref->{$key}) eq 'ARRAY') {
4762: $result.=&arrayref2str($hashref->{$key}).'&';
4763: } elsif(ref($hashref->{$key}) eq 'HASH') {
4764: $result.=&hashref2str($hashref->{$key}).'&';
4765: } elsif(ref($hashref->{$key})) {
1.265 albertel 4766: $result.='&';
1.800 albertel 4767: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4768: } else {
1.800 albertel 4769: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4770: }
4771: }
1.168 albertel 4772: $result=~s/\&$//;
1.265 albertel 4773: $result .= '__END_HASH_REF__';
1.168 albertel 4774: return $result;
4775: }
4776:
4777: sub str2hash {
1.265 albertel 4778: my ($string)=@_;
4779: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4780: return %$hash;
4781: }
4782:
4783: sub str2hashref {
1.168 albertel 4784: my ($string) = @_;
1.265 albertel 4785:
4786: my %hash;
4787:
4788: if($string !~ /^__HASH_REF__/) {
4789: if (! ($string eq '' || !defined($string))) {
4790: $hash{'error'}='Not hash reference';
4791: }
4792: return (\%hash, $string);
4793: }
4794:
4795: $string =~ s/^__HASH_REF__//;
4796:
4797: while($string !~ /^__END_HASH_REF__/) {
4798: #key
4799: my $key='';
4800: if($string =~ /^__HASH_REF__/) {
4801: ($key, $string)=&str2hashref($string);
4802: if(defined($key->{'error'})) {
4803: $hash{'error'}='Bad data';
4804: return (\%hash, $string);
4805: }
4806: } elsif($string =~ /^__ARRAY_REF__/) {
4807: ($key, $string)=&str2arrayref($string);
4808: if($key->[0] eq 'Array reference error') {
4809: $hash{'error'}='Bad data';
4810: return (\%hash, $string);
4811: }
4812: } else {
4813: $string =~ s/^(.*?)=//;
1.267 albertel 4814: $key=&unescape($1);
1.265 albertel 4815: }
4816: $string =~ s/^=//;
4817:
4818: #value
4819: my $value='';
4820: if($string =~ /^__HASH_REF__/) {
4821: ($value, $string)=&str2hashref($string);
4822: if(defined($value->{'error'})) {
4823: $hash{'error'}='Bad data';
4824: return (\%hash, $string);
4825: }
4826: } elsif($string =~ /^__ARRAY_REF__/) {
4827: ($value, $string)=&str2arrayref($string);
4828: if($value->[0] eq 'Array reference error') {
4829: $hash{'error'}='Bad data';
4830: return (\%hash, $string);
4831: }
4832: } else {
4833: $value=&get_scalar(\$string,'__END_HASH_REF__');
4834: }
4835: $string =~ s/^&//;
4836:
4837: $hash{$key}=$value;
1.204 albertel 4838: }
1.265 albertel 4839:
4840: $string =~ s/^__END_HASH_REF__//;
4841:
4842: return (\%hash, $string);
1.204 albertel 4843: }
4844:
4845: sub str2array {
1.265 albertel 4846: my ($string)=@_;
4847: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4848: return @$array;
4849: }
4850:
4851: sub str2arrayref {
1.204 albertel 4852: my ($string) = @_;
1.265 albertel 4853: my @array;
4854:
4855: if($string !~ /^__ARRAY_REF__/) {
4856: if (! ($string eq '' || !defined($string))) {
4857: $array[0]='Array reference error';
4858: }
4859: return (\@array, $string);
4860: }
4861:
4862: $string =~ s/^__ARRAY_REF__//;
4863:
4864: while($string !~ /^__END_ARRAY_REF__/) {
4865: my $value='';
4866: if($string =~ /^__HASH_REF__/) {
4867: ($value, $string)=&str2hashref($string);
4868: if(defined($value->{'error'})) {
4869: $array[0] ='Array reference error';
4870: return (\@array, $string);
4871: }
4872: } elsif($string =~ /^__ARRAY_REF__/) {
4873: ($value, $string)=&str2arrayref($string);
4874: if($value->[0] eq 'Array reference error') {
4875: $array[0] ='Array reference error';
4876: return (\@array, $string);
4877: }
4878: } else {
4879: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4880: }
4881: $string =~ s/^&//;
4882:
4883: push(@array, $value);
1.191 harris41 4884: }
1.265 albertel 4885:
4886: $string =~ s/^__END_ARRAY_REF__//;
4887:
4888: return (\@array, $string);
1.168 albertel 4889: }
4890:
1.167 albertel 4891: # -------------------------------------------------------------------Temp Store
4892:
1.168 albertel 4893: sub tmpreset {
4894: my ($symb,$namespace,$domain,$stuname) = @_;
4895: if (!$symb) {
4896: $symb=&symbread();
1.620 albertel 4897: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4898: }
4899: $symb=escape($symb);
4900:
1.620 albertel 4901: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4902: $namespace=~s/\//\_/g;
4903: $namespace=~s/\W//g;
4904:
1.620 albertel 4905: if (!$domain) { $domain=$env{'user.domain'}; }
4906: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4907: if ($domain eq 'public' && $stuname eq 'public') {
4908: $stuname=$ENV{'REMOTE_ADDR'};
4909: }
1.1117 foxr 4910: my $path=LONCAPA::tempdir();
1.168 albertel 4911: my %hash;
4912: if (tie(%hash,'GDBM_File',
4913: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4914: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4915: foreach my $key (keys(%hash)) {
1.180 albertel 4916: if ($key=~ /:$symb/) {
1.168 albertel 4917: delete($hash{$key});
4918: }
4919: }
4920: }
4921: }
4922:
1.167 albertel 4923: sub tmpstore {
1.168 albertel 4924: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4925:
4926: if (!$symb) {
4927: $symb=&symbread();
1.620 albertel 4928: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4929: }
4930: $symb=escape($symb);
4931:
4932: if (!$namespace) {
4933: # I don't think we would ever want to store this for a course.
4934: # it seems this will only be used if we don't have a course.
1.620 albertel 4935: #$namespace=$env{'request.course.id'};
1.168 albertel 4936: #if (!$namespace) {
1.620 albertel 4937: $namespace=$env{'request.state'};
1.168 albertel 4938: #}
4939: }
4940: $namespace=~s/\//\_/g;
4941: $namespace=~s/\W//g;
1.620 albertel 4942: if (!$domain) { $domain=$env{'user.domain'}; }
4943: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4944: if ($domain eq 'public' && $stuname eq 'public') {
4945: $stuname=$ENV{'REMOTE_ADDR'};
4946: }
1.168 albertel 4947: my $now=time;
4948: my %hash;
1.1117 foxr 4949: my $path=LONCAPA::tempdir();
1.168 albertel 4950: if (tie(%hash,'GDBM_File',
4951: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4952: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4953: $hash{"version:$symb"}++;
4954: my $version=$hash{"version:$symb"};
4955: my $allkeys='';
4956: foreach my $key (keys(%$storehash)) {
4957: $allkeys.=$key.':';
1.591 albertel 4958: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4959: }
4960: $hash{"$version:$symb:timestamp"}=$now;
4961: $allkeys.='timestamp';
4962: $hash{"$version:keys:$symb"}=$allkeys;
4963: if (untie(%hash)) {
4964: return 'ok';
4965: } else {
4966: return "error:$!";
4967: }
4968: } else {
4969: return "error:$!";
4970: }
4971: }
1.167 albertel 4972:
1.168 albertel 4973: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4974:
1.168 albertel 4975: sub tmprestore {
4976: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4977:
1.168 albertel 4978: if (!$symb) {
4979: $symb=&symbread();
1.620 albertel 4980: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4981: }
4982: $symb=escape($symb);
4983:
1.620 albertel 4984: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4985:
1.620 albertel 4986: if (!$domain) { $domain=$env{'user.domain'}; }
4987: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4988: if ($domain eq 'public' && $stuname eq 'public') {
4989: $stuname=$ENV{'REMOTE_ADDR'};
4990: }
1.168 albertel 4991: my %returnhash;
4992: $namespace=~s/\//\_/g;
4993: $namespace=~s/\W//g;
4994: my %hash;
1.1117 foxr 4995: my $path=LONCAPA::tempdir();
1.168 albertel 4996: if (tie(%hash,'GDBM_File',
4997: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4998: &GDBM_READER(),0640)) {
1.168 albertel 4999: my $version=$hash{"version:$symb"};
5000: $returnhash{'version'}=$version;
5001: my $scope;
5002: for ($scope=1;$scope<=$version;$scope++) {
5003: my $vkeys=$hash{"$scope:keys:$symb"};
5004: my @keys=split(/:/,$vkeys);
5005: my $key;
5006: $returnhash{"$scope:keys"}=$vkeys;
5007: foreach $key (@keys) {
1.591 albertel 5008: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5009: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5010: }
5011: }
1.168 albertel 5012: if (!(untie(%hash))) {
5013: return "error:$!";
5014: }
5015: } else {
5016: return "error:$!";
5017: }
5018: return %returnhash;
1.167 albertel 5019: }
5020:
1.9 www 5021: # ----------------------------------------------------------------------- Store
5022:
5023: sub store {
1.1172.2.64 raeburn 5024: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5025: my $home='';
5026:
1.168 albertel 5027: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5028:
1.213 www 5029: $symb=&symbclean($symb);
1.122 albertel 5030: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5031:
1.620 albertel 5032: if (!$domain) { $domain=$env{'user.domain'}; }
5033: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5034:
5035: &devalidate($symb,$stuname,$domain);
1.109 www 5036:
5037: $symb=escape($symb);
1.187 www 5038: if (!$namespace) {
1.620 albertel 5039: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5040: return '';
5041: }
5042: }
1.620 albertel 5043: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5044:
5045: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5046: $$storehash{'host'}=$perlvar{'lonHostID'};
5047:
1.12 www 5048: my $namevalue='';
1.800 albertel 5049: foreach my $key (keys(%$storehash)) {
5050: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5051: }
1.12 www 5052: $namevalue=~s/\&$//;
1.187 www 5053: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 5054: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5055: }
5056:
1.47 www 5057: # -------------------------------------------------------------- Critical Store
5058:
5059: sub cstore {
1.1172.2.64 raeburn 5060: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5061: my $home='';
5062:
1.168 albertel 5063: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5064:
1.213 www 5065: $symb=&symbclean($symb);
1.122 albertel 5066: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5067:
1.620 albertel 5068: if (!$domain) { $domain=$env{'user.domain'}; }
5069: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5070:
5071: &devalidate($symb,$stuname,$domain);
1.109 www 5072:
5073: $symb=escape($symb);
1.187 www 5074: if (!$namespace) {
1.620 albertel 5075: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5076: return '';
5077: }
5078: }
1.620 albertel 5079: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5080:
5081: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5082: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5083:
1.47 www 5084: my $namevalue='';
1.800 albertel 5085: foreach my $key (keys(%$storehash)) {
5086: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5087: }
1.47 www 5088: $namevalue=~s/\&$//;
1.187 www 5089: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5090: return critical
1.1172.2.64 raeburn 5091: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5092: }
5093:
1.9 www 5094: # --------------------------------------------------------------------- Restore
5095:
5096: sub restore {
1.124 www 5097: my ($symb,$namespace,$domain,$stuname) = @_;
5098: my $home='';
5099:
1.168 albertel 5100: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5101:
1.122 albertel 5102: if (!$symb) {
1.1172.2.26 raeburn 5103: return if ($namespace eq 'courserequests');
5104: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5105: } else {
1.1172.2.26 raeburn 5106: unless ($namespace eq 'courserequests') {
5107: $symb=&escape(&symbclean($symb));
5108: }
1.122 albertel 5109: }
1.188 www 5110: if (!$namespace) {
1.620 albertel 5111: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5112: return '';
5113: }
5114: }
1.620 albertel 5115: if (!$domain) { $domain=$env{'user.domain'}; }
5116: if (!$stuname) { $stuname=$env{'user.name'}; }
5117: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5118: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5119:
1.12 www 5120: my %returnhash=();
1.800 albertel 5121: foreach my $line (split(/\&/,$answer)) {
5122: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5123: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5124: }
1.75 www 5125: my $version;
5126: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5127: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5128: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5129: }
1.75 www 5130: }
1.13 www 5131: return %returnhash;
1.34 www 5132: }
5133:
5134: # ---------------------------------------------------------- Course Description
1.1118 foxr 5135: #
5136: #
1.34 www 5137:
5138: sub coursedescription {
1.731 albertel 5139: my ($courseid,$args)=@_;
1.34 www 5140: $courseid=~s/^\///;
1.49 www 5141: $courseid=~s/\_/\//g;
1.34 www 5142: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5143: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5144: my $normalid=$cdomain.'_'.$cnum;
5145: # need to always cache even if we get errors otherwise we keep
5146: # trying and trying and trying to get the course description.
5147: my %envhash=();
5148: my %returnhash=();
1.731 albertel 5149:
5150: my $expiretime=600;
5151: if ($env{'request.course.id'} eq $normalid) {
5152: $expiretime=120;
5153: }
5154:
5155: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5156: if (!$args->{'freshen_cache'}
5157: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5158: foreach my $key (keys(%env)) {
5159: next if ($key !~ /^\Q$prefix\E(.*)/);
5160: my ($setting) = $1;
5161: $returnhash{$setting} = $env{$key};
5162: }
5163: return %returnhash;
5164: }
5165:
1.1118 foxr 5166: # get the data again
5167:
1.731 albertel 5168: if (!$args->{'one_time'}) {
5169: $envhash{'course.'.$normalid.'.last_cache'}=time;
5170: }
1.811 albertel 5171:
1.34 www 5172: if ($chome ne 'no_host') {
1.302 albertel 5173: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5174: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5175: my $username = $env{'user.name'}; # Defult username
5176: if(defined $args->{'user'}) {
5177: $username = $args->{'user'};
5178: }
1.129 albertel 5179: $returnhash{'home'}= $chome;
5180: $returnhash{'domain'} = $cdomain;
5181: $returnhash{'num'} = $cnum;
1.741 raeburn 5182: if (!defined($returnhash{'type'})) {
5183: $returnhash{'type'} = 'Course';
5184: }
1.130 albertel 5185: while (my ($name,$value) = each %returnhash) {
1.53 www 5186: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5187: }
1.270 www 5188: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5189: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5190: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5191: $envhash{'course.'.$normalid.'.home'}=$chome;
5192: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5193: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5194: }
5195: }
1.731 albertel 5196: if (!$args->{'one_time'}) {
1.949 raeburn 5197: &appenv(\%envhash);
1.731 albertel 5198: }
1.302 albertel 5199: return %returnhash;
1.461 www 5200: }
5201:
1.1080 raeburn 5202: sub update_released_required {
5203: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5204: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5205: $cid = $env{'request.course.id'};
5206: $cdom = $env{'course.'.$cid.'.domain'};
5207: $cnum = $env{'course.'.$cid.'.num'};
5208: $chome = $env{'course.'.$cid.'.home'};
5209: }
5210: if ($needsrelease) {
5211: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5212: my $needsupdate;
5213: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5214: $needsupdate = 1;
5215: } else {
5216: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5217: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5218: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5219: $needsupdate = 1;
5220: }
5221: }
5222: if ($needsupdate) {
5223: my %needshash = (
5224: 'internal.releaserequired' => $needsrelease,
5225: );
5226: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5227: if ($putresult eq 'ok') {
5228: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5229: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5230: if (ref($crsinfo{$cid}) eq 'HASH') {
5231: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5232: &courseidput($cdom,\%crsinfo,$chome,'notime');
5233: }
5234: }
5235: }
5236: }
5237: return;
5238: }
5239:
1.461 www 5240: # -------------------------------------------------See if a user is privileged
5241:
5242: sub privileged {
1.1172.2.23 raeburn 5243: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5244: my $now = time;
1.1172.2.23 raeburn 5245: my $roles;
5246: if (ref($possroles) eq 'ARRAY') {
5247: $roles = $possroles;
5248: } else {
5249: $roles = ['dc','su'];
5250: }
5251: if (ref($possdomains) eq 'ARRAY') {
5252: my %privileged = &privileged_by_domain($possdomains,$roles);
5253: foreach my $dom (@{$possdomains}) {
5254: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5255: (ref($privileged{$dom}) eq 'HASH')) {
5256: foreach my $role (@{$roles}) {
5257: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5258: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5259: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5260: return 1 unless (($end && $end < $now) ||
5261: ($start && $start > $now));
5262: }
5263: }
5264: }
5265: }
5266: }
5267: } else {
5268: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5269: my $now = time;
1.1170 droeschl 5270:
1.1172.2.58 raeburn 5271: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5272: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 5273: if (grep(/^\Q$trole\E$/,@{$roles})) {
5274: return 1 unless ($tend && $tend < $now)
5275: or ($tstart && $tstart > $now);
1.1170 droeschl 5276: }
1.1172.2.23 raeburn 5277: }
5278: }
1.461 www 5279: return 0;
1.9 www 5280: }
1.1 albertel 5281:
1.1172.2.23 raeburn 5282: sub privileged_by_domain {
5283: my ($domains,$roles) = @_;
5284: my %privileged = ();
5285: my $cachetime = 60*60*24;
5286: my $now = time;
5287: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5288: return %privileged;
5289: }
5290: foreach my $dom (@{$domains}) {
5291: next if (ref($privileged{$dom}) eq 'HASH');
5292: my $needroles;
5293: foreach my $role (@{$roles}) {
5294: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5295: if (defined($cached)) {
5296: if (ref($result) eq 'HASH') {
5297: $privileged{$dom}{$role} = $result;
5298: }
5299: } else {
5300: $needroles = 1;
5301: }
5302: }
5303: if ($needroles) {
5304: my %dompersonnel = &get_domain_roles($dom,$roles);
5305: $privileged{$dom} = {};
5306: foreach my $server (keys(%dompersonnel)) {
5307: if (ref($dompersonnel{$server}) eq 'HASH') {
5308: foreach my $item (keys(%{$dompersonnel{$server}})) {
5309: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5310: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5311: next if ($end && $end < $now);
5312: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5313: $dompersonnel{$server}{$item};
5314: }
5315: }
5316: }
5317: if (ref($privileged{$dom}) eq 'HASH') {
5318: foreach my $role (@{$roles}) {
5319: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5320: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5321: } else {
5322: my %hash = ();
5323: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5324: }
5325: }
5326: }
5327: }
5328: }
5329: return %privileged;
5330: }
5331:
1.103 harris41 5332: # -------------------------------------------------------- Get user privileges
1.11 www 5333:
5334: sub rolesinit {
1.1169 droeschl 5335: my ($domain, $username) = @_;
5336: my %userroles = ('user.login.time' => time);
5337: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5338:
5339: # firstaccess and timerinterval are related to timed maps/resources.
5340: # also, blocking can be triggered by an activating timer
5341: # it's saved in the user's %env.
5342: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5343: my %timerinterval = &dump('timerinterval', $domain, $username);
5344: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5345: %timerintchk, %timerintenv);
5346:
1.1162 raeburn 5347: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5348: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5349: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5350: }
1.1169 droeschl 5351:
1.1162 raeburn 5352: foreach my $key (keys(%timerinterval)) {
5353: my ($cid,$rest) = split(/\0/,$key);
5354: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5355: }
1.1169 droeschl 5356:
1.11 www 5357: my %allroles=();
1.1162 raeburn 5358: my %allgroups=();
1.11 www 5359:
1.1172.2.58 raeburn 5360: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5361: my $role = $rolesdump{$area};
5362: $area =~ s/\_\w\w$//;
5363:
5364: my ($trole, $tend, $tstart, $group_privs);
5365:
5366: if ($role =~ /^cr/) {
5367: # Custom role, defined by a user
5368: # e.g., user.role.cr/msu/smith/mynewrole
5369: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5370: $trole = $1;
5371: ($tend, $tstart) = split('_', $2);
5372: } else {
5373: $trole = $role;
5374: }
5375: } elsif ($role =~ m|^gr/|) {
5376: # Role of member in a group, defined within a course/community
5377: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5378: ($trole, $tend, $tstart) = split(/_/, $role);
5379: next if $tstart eq '-1';
5380: ($trole, $group_privs) = split(/\//, $trole);
5381: $group_privs = &unescape($group_privs);
5382: } else {
5383: # Just a normal role, defined in roles.tab
5384: ($trole, $tend, $tstart) = split(/_/,$role);
5385: }
5386:
5387: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5388: $username);
5389: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5390:
5391: # role expired or not available yet?
5392: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5393: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5394:
5395: next if $area eq '' or $trole eq '';
5396:
5397: my $spec = "$trole.$area";
5398: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5399:
5400: if ($trole =~ /^cr\//) {
5401: # Custom role, defined by a user
5402: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5403: } elsif ($trole eq 'gr') {
5404: # Role of a member in a group, defined within a course/community
5405: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5406: next;
5407: } else {
5408: # Normal role, defined in roles.tab
5409: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5410: }
5411:
5412: my $cid = $tdomain.'_'.$trest;
5413: unless ($firstaccchk{$cid}) {
5414: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5415: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5416: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5417: $coursetimerstarts{$cid}{$item};
5418: }
5419: }
5420: $firstaccchk{$cid} = 1;
5421: }
5422: unless ($timerintchk{$cid}) {
5423: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5424: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5425: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5426: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5427: }
1.12 www 5428: }
1.1169 droeschl 5429: $timerintchk{$cid} = 1;
1.191 harris41 5430: }
1.11 www 5431: }
1.1169 droeschl 5432:
5433: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5434: \%allroles, \%allgroups);
5435: $env{'user.adv'} = $userroles{'user.adv'};
5436:
1.1162 raeburn 5437: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5438: }
5439:
1.567 raeburn 5440: sub set_arearole {
1.1172.2.19 raeburn 5441: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5442: unless ($nolog) {
1.567 raeburn 5443: # log the associated role with the area
1.1172.2.19 raeburn 5444: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5445: }
1.743 albertel 5446: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5447: }
5448:
5449: sub custom_roleprivs {
5450: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5451: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 5452: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5453: if (&hostname($homsvr) ne '') {
1.567 raeburn 5454: my ($rdummy,$roledef)=
5455: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5456: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5457: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5458: if (defined($syspriv)) {
1.1043 raeburn 5459: if ($trest =~ /^$match_community$/) {
5460: $syspriv =~ s/bre\&S//;
5461: }
1.567 raeburn 5462: $$allroles{'cm./'}.=':'.$syspriv;
5463: $$allroles{$spec.'./'}.=':'.$syspriv;
5464: }
5465: if ($tdomain ne '') {
5466: if (defined($dompriv)) {
5467: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5468: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5469: }
5470: if (($trest ne '') && (defined($coursepriv))) {
5471: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5472: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5473: }
5474: }
5475: }
5476: }
5477: }
5478:
1.678 raeburn 5479: sub group_roleprivs {
5480: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5481: my $access = 1;
5482: my $now = time;
5483: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5484: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5485: if ($access) {
1.811 albertel 5486: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5487: $$allgroups{$course}{$group} .=':'.$group_privs;
5488: }
5489: }
1.567 raeburn 5490:
5491: sub standard_roleprivs {
5492: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5493: if (defined($pr{$trole.':s'})) {
5494: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5495: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5496: }
5497: if ($tdomain ne '') {
5498: if (defined($pr{$trole.':d'})) {
5499: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5500: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5501: }
5502: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5503: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5504: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5505: }
5506: }
5507: }
5508:
5509: sub set_userprivs {
1.1064 raeburn 5510: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5511: my $author=0;
5512: my $adv=0;
1.678 raeburn 5513: my %grouproles = ();
5514: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5515: my @groupkeys;
1.1000 raeburn 5516: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5517: push(@groupkeys,$role);
5518: }
5519: if (ref($groups_roles) eq 'HASH') {
5520: foreach my $key (keys(%{$groups_roles})) {
5521: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5522: push(@groupkeys,$key);
5523: }
5524: }
5525: }
5526: if (@groupkeys > 0) {
5527: foreach my $role (@groupkeys) {
5528: my ($trole,$area,$sec,$extendedarea);
5529: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5530: $trole = $1;
5531: $area = $2;
5532: $sec = $3;
5533: $extendedarea = $area.$sec;
5534: if (exists($$allgroups{$area})) {
5535: foreach my $group (keys(%{$$allgroups{$area}})) {
5536: my $spec = $trole.'.'.$extendedarea;
5537: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5538: $$allgroups{$area}{$group};
1.1064 raeburn 5539: }
1.678 raeburn 5540: }
5541: }
5542: }
5543: }
5544: }
1.800 albertel 5545: foreach my $group (keys(%grouproles)) {
5546: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5547: }
1.800 albertel 5548: foreach my $role (keys(%{$allroles})) {
5549: my %thesepriv;
1.941 raeburn 5550: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5551: foreach my $item (split(/:/,$$allroles{$role})) {
5552: if ($item ne '') {
5553: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5554: if ($restrictions eq '') {
5555: $thesepriv{$privilege}='F';
5556: } elsif ($thesepriv{$privilege} ne 'F') {
5557: $thesepriv{$privilege}.=$restrictions;
5558: }
5559: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5560: }
5561: }
5562: my $thesestr='';
1.1104 raeburn 5563: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5564: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5565: }
5566: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5567: }
5568: return ($author,$adv);
5569: }
5570:
1.994 raeburn 5571: sub role_status {
1.1104 raeburn 5572: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5573: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 5574: my ($one,$two) = split(m{\./},$rolekey,2);
5575: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5576: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 5577: $$where = '/'.$two;
1.994 raeburn 5578: $$trolecode=$$role.'.'.$$where;
5579: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5580: $$tstatus='is';
1.1104 raeburn 5581: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5582: $$tstatus='future';
1.1034 raeburn 5583: if ($$tstart<$now) {
5584: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5585: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5586: my (%allroles,%allgroups,$group_privs,
5587: %groups_roles,@rolecodes);
1.1002 raeburn 5588: my %userroles = (
5589: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5590: );
1.1064 raeburn 5591: @rolecodes = ('cm');
1.1002 raeburn 5592: my $spec=$$role.'.'.$$where;
5593: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5594: if ($$role =~ /^cr\//) {
5595: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5596: push(@rolecodes,'cr');
1.1002 raeburn 5597: } elsif ($$role eq 'gr') {
1.1064 raeburn 5598: push(@rolecodes,$$role);
1.1002 raeburn 5599: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5600: $env{'user.name'});
1.1064 raeburn 5601: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5602: (undef,my $group_privs) = split(/\//,$trole);
5603: $group_privs = &unescape($group_privs);
5604: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5605: 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 5606: &get_groups_roles($tdomain,$trest,
5607: \%course_roles,\@rolecodes,
5608: \%groups_roles);
1.1002 raeburn 5609: } else {
1.1064 raeburn 5610: push(@rolecodes,$$role);
1.1002 raeburn 5611: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5612: }
1.1064 raeburn 5613: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5614: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5615: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5616: }
5617: }
1.1034 raeburn 5618: $$tstatus = 'is';
1.1002 raeburn 5619: }
1.994 raeburn 5620: }
5621: if ($$tend) {
1.1104 raeburn 5622: if ($$tend<$update) {
1.994 raeburn 5623: $$tstatus='expired';
5624: } elsif ($$tend<$now) {
5625: $$tstatus='will_not';
5626: }
5627: }
5628: }
5629: }
5630: }
5631:
1.1104 raeburn 5632: sub get_groups_roles {
5633: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5634: return unless((ref($cdom_courseroles) eq 'HASH') &&
5635: (ref($rolecodes) eq 'ARRAY') &&
5636: (ref($groups_roles) eq 'HASH'));
5637: if (keys(%{$cdom_courseroles}) > 0) {
5638: my ($cnum) = ($rest =~ /^($match_courseid)/);
5639: if ($cdom ne '' && $cnum ne '') {
5640: foreach my $key (keys(%{$cdom_courseroles})) {
5641: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5642: my $crsrole = $1;
5643: my $crssec = $2;
5644: if ($crsrole =~ /^cr/) {
5645: unless (grep(/^cr$/,@{$rolecodes})) {
5646: push(@{$rolecodes},'cr');
5647: }
5648: } else {
5649: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5650: push(@{$rolecodes},$crsrole);
5651: }
5652: }
5653: my $rolekey = "$crsrole./$cdom/$cnum";
5654: if ($crssec ne '') {
5655: $rolekey .= "/$crssec";
5656: }
5657: $rolekey .= './';
5658: $groups_roles->{$rolekey} = $rolecodes;
5659: }
5660: }
5661: }
5662: }
5663: return;
5664: }
5665:
5666: sub delete_env_groupprivs {
5667: my ($where,$courseroles,$possroles) = @_;
5668: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5669: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5670: unless (ref($courseroles->{$udom}) eq 'HASH') {
5671: %{$courseroles->{$udom}} =
5672: &get_my_roles('','','userroles',['active'],
5673: $possroles,[$udom],1);
5674: }
5675: if (ref($courseroles->{$udom}) eq 'HASH') {
5676: foreach my $item (keys(%{$courseroles->{$udom}})) {
5677: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5678: my $area = '/'.$cdom.'/'.$cnum;
5679: my $privkey = "user.priv.$crsrole.$area";
5680: if ($crssec ne '') {
5681: $privkey .= '/'.$crssec;
5682: }
5683: $privkey .= ".$area/$group";
5684: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5685: }
5686: }
5687: return;
5688: }
5689:
1.994 raeburn 5690: sub check_adhoc_privs {
1.1104 raeburn 5691: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5692: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9 raeburn 5693: my $setprivs;
1.994 raeburn 5694: if ($env{$cckey}) {
5695: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5696: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5697: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5698: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5699: $setprivs = 1;
1.994 raeburn 5700: }
5701: } else {
1.1088 raeburn 5702: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9 raeburn 5703: $setprivs = 1;
1.994 raeburn 5704: }
1.1172.2.9 raeburn 5705: return $setprivs;
1.994 raeburn 5706: }
5707:
5708: sub set_adhoc_privileges {
5709: # role can be cc or ca
1.1088 raeburn 5710: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5711: my $area = '/'.$dcdom.'/'.$pickedcourse;
5712: my $spec = $role.'.'.$area;
5713: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 5714: $env{'user.name'},1);
1.994 raeburn 5715: my %ccrole = ();
5716: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5717: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5718: &appenv(\%userroles,[$role,'cm']);
5719: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5720: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5721: &appenv( {'request.role' => $spec,
5722: 'request.role.domain' => $dcdom,
5723: 'request.course.sec' => ''
5724: }
5725: );
5726: my $tadv=0;
5727: if (&allowed('adv') eq 'F') { $tadv=1; }
5728: &appenv({'request.role.adv' => $tadv});
5729: }
1.994 raeburn 5730: }
5731:
1.12 www 5732: # --------------------------------------------------------------- get interface
5733:
5734: sub get {
1.131 albertel 5735: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5736: my $items='';
1.800 albertel 5737: foreach my $item (@$storearr) {
5738: $items.=&escape($item).'&';
1.191 harris41 5739: }
1.12 www 5740: $items=~s/\&$//;
1.620 albertel 5741: if (!$udomain) { $udomain=$env{'user.domain'}; }
5742: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5743: my $uhome=&homeserver($uname,$udomain);
5744:
1.133 albertel 5745: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5746: my @pairs=split(/\&/,$rep);
1.273 albertel 5747: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5748: return @pairs;
5749: }
1.15 www 5750: my %returnhash=();
1.42 www 5751: my $i=0;
1.800 albertel 5752: foreach my $item (@$storearr) {
5753: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5754: $i++;
1.191 harris41 5755: }
1.15 www 5756: return %returnhash;
1.27 www 5757: }
5758:
5759: # --------------------------------------------------------------- del interface
5760:
5761: sub del {
1.133 albertel 5762: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5763: my $items='';
1.800 albertel 5764: foreach my $item (@$storearr) {
5765: $items.=&escape($item).'&';
1.191 harris41 5766: }
1.984 neumanie 5767:
1.27 www 5768: $items=~s/\&$//;
1.620 albertel 5769: if (!$udomain) { $udomain=$env{'user.domain'}; }
5770: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5771: my $uhome=&homeserver($uname,$udomain);
5772: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5773: }
5774:
5775: # -------------------------------------------------------------- dump interface
5776:
1.1172.2.22 raeburn 5777: sub unserialize {
5778: my ($rep, $escapedkeys) = @_;
5779:
5780: return {} if $rep =~ /^error/;
5781:
5782: my %returnhash=();
5783: foreach my $item (split(/\&/,$rep)) {
5784: my ($key, $value) = split(/=/, $item, 2);
5785: $key = unescape($key) unless $escapedkeys;
5786: next if $key =~ /^error: 2 /;
5787: $returnhash{$key} = &thaw_unescape($value);
5788: }
5789: return \%returnhash;
5790: }
5791:
5792: # see Lond::dump_with_regexp
5793: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5794: sub dump {
1.1172.2.22 raeburn 5795: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5796: if (!$udomain) { $udomain=$env{'user.domain'}; }
5797: if (!$uname) { $uname=$env{'user.name'}; }
5798: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5799:
1.1172.2.55 raeburn 5800: if ($regexp) {
5801: $regexp=&escape($regexp);
5802: } else {
5803: $regexp='.';
5804: }
1.1172.2.22 raeburn 5805: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
5806: # user is hosted on this machine
1.1172.2.55 raeburn 5807: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 5808: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 5809: return %{&unserialize($reply, $escapedkeys)};
5810: }
1.1166 raeburn 5811: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5812: my @pairs=split(/\&/,$rep);
5813: my %returnhash=();
1.1098 foxr 5814: if (!($rep =~ /^error/ )) {
5815: foreach my $item (@pairs) {
5816: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 5817: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 5818: next if ($key =~ /^error: 2 /);
5819: $returnhash{$key}=&thaw_unescape($value);
5820: }
1.755 albertel 5821: }
5822: return %returnhash;
1.407 www 5823: }
5824:
1.1098 foxr 5825:
1.717 albertel 5826: # --------------------------------------------------------- dumpstore interface
5827:
5828: sub dumpstore {
5829: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 5830: # same as dump but keys must be escaped. They may contain colon separated
5831: # lists of values that may themself contain colons (e.g. symbs).
5832: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5833: }
5834:
1.407 www 5835: # -------------------------------------------------------------- keys interface
5836:
5837: sub getkeys {
5838: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5839: if (!$udomain) { $udomain=$env{'user.domain'}; }
5840: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5841: my $uhome=&homeserver($uname,$udomain);
5842: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5843: my @keyarray=();
1.800 albertel 5844: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5845: next if ($key =~ /^error: 2 /);
1.800 albertel 5846: push(@keyarray,&unescape($key));
1.407 www 5847: }
5848: return @keyarray;
1.318 matthew 5849: }
5850:
1.319 matthew 5851: # --------------------------------------------------------------- currentdump
5852: sub currentdump {
1.328 matthew 5853: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5854: $courseid = $env{'request.course.id'} if (! defined($courseid));
5855: $sdom = $env{'user.domain'} if (! defined($sdom));
5856: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5857: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 5858: my $rep;
5859:
5860: if (grep { $_ eq $uhome } current_machine_ids()) {
5861: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5862: $courseid)));
5863: } else {
5864: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5865: }
5866:
1.318 matthew 5867: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5868: #
1.318 matthew 5869: my %returnhash=();
1.319 matthew 5870: #
5871: if ($rep eq "unknown_cmd") {
5872: # an old lond will not know currentdump
5873: # Do a dump and make it look like a currentdump
1.822 albertel 5874: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5875: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5876: my %hash = @tmp;
5877: @tmp=();
1.424 matthew 5878: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5879: } else {
5880: my @pairs=split(/\&/,$rep);
1.800 albertel 5881: foreach my $pair (@pairs) {
5882: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5883: my ($symb,$param) = split(/:/,$key);
5884: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5885: &thaw_unescape($value);
1.319 matthew 5886: }
1.191 harris41 5887: }
1.12 www 5888: return %returnhash;
1.424 matthew 5889: }
5890:
5891: sub convert_dump_to_currentdump{
5892: my %hash = %{shift()};
5893: my %returnhash;
5894: # Code ripped from lond, essentially. The only difference
5895: # here is the unescaping done by lonnet::dump(). Conceivably
5896: # we might run in to problems with parameter names =~ /^v\./
5897: while (my ($key,$value) = each(%hash)) {
5898: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5899: $symb = &unescape($symb);
5900: $param = &unescape($param);
1.424 matthew 5901: next if ($v eq 'version' || $symb eq 'keys');
5902: next if (exists($returnhash{$symb}) &&
5903: exists($returnhash{$symb}->{$param}) &&
5904: $returnhash{$symb}->{'v.'.$param} > $v);
5905: $returnhash{$symb}->{$param}=$value;
5906: $returnhash{$symb}->{'v.'.$param}=$v;
5907: }
5908: #
5909: # Remove all of the keys in the hashes which keep track of
5910: # the version of the parameter.
5911: while (my ($symb,$param_hash) = each(%returnhash)) {
5912: # use a foreach because we are going to delete from the hash.
5913: foreach my $key (keys(%$param_hash)) {
5914: delete($param_hash->{$key}) if ($key =~ /^v\./);
5915: }
5916: }
5917: return \%returnhash;
1.12 www 5918: }
5919:
1.627 albertel 5920: # ------------------------------------------------------ critical inc interface
5921:
5922: sub cinc {
5923: return &inc(@_,'critical');
5924: }
5925:
1.449 matthew 5926: # --------------------------------------------------------------- inc interface
5927:
5928: sub inc {
1.627 albertel 5929: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5930: if (!$udomain) { $udomain=$env{'user.domain'}; }
5931: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5932: my $uhome=&homeserver($uname,$udomain);
5933: my $items='';
5934: if (! ref($store)) {
5935: # got a single value, so use that instead
5936: $items = &escape($store).'=&';
5937: } elsif (ref($store) eq 'SCALAR') {
5938: $items = &escape($$store).'=&';
5939: } elsif (ref($store) eq 'ARRAY') {
5940: $items = join('=&',map {&escape($_);} @{$store});
5941: } elsif (ref($store) eq 'HASH') {
5942: while (my($key,$value) = each(%{$store})) {
5943: $items.= &escape($key).'='.&escape($value).'&';
5944: }
5945: }
5946: $items=~s/\&$//;
1.627 albertel 5947: if ($critical) {
5948: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5949: } else {
5950: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5951: }
1.449 matthew 5952: }
5953:
1.12 www 5954: # --------------------------------------------------------------- put interface
5955:
5956: sub put {
1.134 albertel 5957: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5958: if (!$udomain) { $udomain=$env{'user.domain'}; }
5959: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5960: my $uhome=&homeserver($uname,$udomain);
1.12 www 5961: my $items='';
1.800 albertel 5962: foreach my $item (keys(%$storehash)) {
5963: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5964: }
1.12 www 5965: $items=~s/\&$//;
1.134 albertel 5966: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5967: }
5968:
1.631 albertel 5969: # ------------------------------------------------------------ newput interface
5970:
5971: sub newput {
5972: my ($namespace,$storehash,$udomain,$uname)=@_;
5973: if (!$udomain) { $udomain=$env{'user.domain'}; }
5974: if (!$uname) { $uname=$env{'user.name'}; }
5975: my $uhome=&homeserver($uname,$udomain);
5976: my $items='';
5977: foreach my $key (keys(%$storehash)) {
5978: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5979: }
5980: $items=~s/\&$//;
5981: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5982: }
5983:
5984: # --------------------------------------------------------- putstore interface
5985:
1.524 raeburn 5986: sub putstore {
1.1172.2.59 raeburn 5987: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 5988: if (!$udomain) { $udomain=$env{'user.domain'}; }
5989: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5990: my $uhome=&homeserver($uname,$udomain);
5991: my $items='';
1.715 albertel 5992: foreach my $key (keys(%$storehash)) {
5993: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5994: }
1.715 albertel 5995: $items=~s/\&$//;
1.716 albertel 5996: my $esc_symb=&escape($symb);
5997: my $esc_v=&escape($version);
1.715 albertel 5998: my $reply =
1.716 albertel 5999: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6000: $uhome);
1.1172.2.59 raeburn 6001: if (($tolog) && ($reply eq 'ok')) {
6002: my $namevalue='';
6003: foreach my $key (keys(%{$storehash})) {
6004: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6005: }
6006: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6007: '&host='.&escape($perlvar{'lonHostID'}).
6008: '&version='.$esc_v.
6009: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6010: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6011: }
1.715 albertel 6012: if ($reply eq 'unknown_cmd') {
1.716 albertel 6013: # gfall back to way things use to be done
1.715 albertel 6014: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6015: $uname);
1.524 raeburn 6016: }
1.715 albertel 6017: return $reply;
6018: }
6019:
6020: sub old_putstore {
1.716 albertel 6021: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6022: if (!$udomain) { $udomain=$env{'user.domain'}; }
6023: if (!$uname) { $uname=$env{'user.name'}; }
6024: my $uhome=&homeserver($uname,$udomain);
6025: my %newstorehash;
1.800 albertel 6026: foreach my $item (keys(%$storehash)) {
6027: my $key = $version.':'.&escape($symb).':'.$item;
6028: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6029: }
6030: my $items='';
6031: my %allitems = ();
1.800 albertel 6032: foreach my $item (keys(%newstorehash)) {
6033: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6034: my $key = $1.':keys:'.$2;
6035: $allitems{$key} .= $3.':';
6036: }
1.800 albertel 6037: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6038: }
1.800 albertel 6039: foreach my $item (keys(%allitems)) {
6040: $allitems{$item} =~ s/\:$//;
6041: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6042: }
6043: $items=~s/\&$//;
6044: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6045: }
6046:
1.47 www 6047: # ------------------------------------------------------ critical put interface
6048:
6049: sub cput {
1.134 albertel 6050: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6051: if (!$udomain) { $udomain=$env{'user.domain'}; }
6052: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6053: my $uhome=&homeserver($uname,$udomain);
1.47 www 6054: my $items='';
1.800 albertel 6055: foreach my $item (keys(%$storehash)) {
6056: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6057: }
1.47 www 6058: $items=~s/\&$//;
1.134 albertel 6059: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6060: }
6061:
6062: # -------------------------------------------------------------- eget interface
6063:
6064: sub eget {
1.133 albertel 6065: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6066: my $items='';
1.800 albertel 6067: foreach my $item (@$storearr) {
6068: $items.=&escape($item).'&';
1.191 harris41 6069: }
1.12 www 6070: $items=~s/\&$//;
1.620 albertel 6071: if (!$udomain) { $udomain=$env{'user.domain'}; }
6072: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6073: my $uhome=&homeserver($uname,$udomain);
6074: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6075: my @pairs=split(/\&/,$rep);
6076: my %returnhash=();
1.42 www 6077: my $i=0;
1.800 albertel 6078: foreach my $item (@$storearr) {
6079: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6080: $i++;
1.191 harris41 6081: }
1.12 www 6082: return %returnhash;
6083: }
6084:
1.667 albertel 6085: # ------------------------------------------------------------ tmpput interface
6086: sub tmpput {
1.802 raeburn 6087: my ($storehash,$server,$context)=@_;
1.667 albertel 6088: my $items='';
1.800 albertel 6089: foreach my $item (keys(%$storehash)) {
6090: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6091: }
6092: $items=~s/\&$//;
1.802 raeburn 6093: if (defined($context)) {
6094: $items .= ':'.&escape($context);
6095: }
1.667 albertel 6096: return &reply("tmpput:$items",$server);
6097: }
6098:
6099: # ------------------------------------------------------------ tmpget interface
6100: sub tmpget {
1.688 albertel 6101: my ($token,$server)=@_;
6102: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6103: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6104: my %returnhash;
6105: foreach my $item (split(/\&/,$rep)) {
6106: my ($key,$value)=split(/=/,$item);
1.951 raeburn 6107: next if ($key =~ /^error: 2 /);
1.667 albertel 6108: $returnhash{&unescape($key)}=&thaw_unescape($value);
6109: }
6110: return %returnhash;
6111: }
6112:
1.1113 raeburn 6113: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6114: sub tmpdel {
6115: my ($token,$server)=@_;
6116: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6117: return &reply("tmpdel:$token",$server);
6118: }
6119:
1.1172.2.13 raeburn 6120: # ------------------------------------------------------------ get_timebased_id
6121:
6122: sub get_timebased_id {
6123: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6124: $maxtries) = @_;
6125: my ($newid,$error,$dellock);
6126: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6127: return ('','ok','invalid call to get suffix');
6128: }
6129:
6130: # set defaults for any optional args for which values were not supplied
6131: if ($who eq '') {
6132: $who = $env{'user.name'}.':'.$env{'user.domain'};
6133: }
6134: if (!$locktries) {
6135: $locktries = 3;
6136: }
6137: if (!$maxtries) {
6138: $maxtries = 10;
6139: }
6140:
6141: if (($cdom eq '') || ($cnum eq '')) {
6142: if ($env{'request.course.id'}) {
6143: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6144: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6145: }
6146: if (($cdom eq '') || ($cnum eq '')) {
6147: return ('','ok','call to get suffix not in course context');
6148: }
6149: }
6150:
6151: # construct locking item
6152: my $lockhash = {
6153: $prefix."\0".'locked_'.$keyid => $who,
6154: };
6155: my $tries = 0;
6156:
6157: # attempt to get lock on nohist_$namespace file
6158: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6159: while (($gotlock ne 'ok') && $tries <$locktries) {
6160: $tries ++;
6161: sleep 1;
6162: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6163: }
6164:
6165: # attempt to get unique identifier, based on current timestamp
6166: if ($gotlock eq 'ok') {
6167: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6168: my $id = time;
6169: $newid = $id;
1.1172.2.56 raeburn 6170: if ($idtype eq 'addcode') {
6171: $newid .= &sixnum_code();
6172: }
1.1172.2.13 raeburn 6173: my $idtries = 0;
6174: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6175: if ($idtype eq 'concat') {
6176: $newid = $id.$idtries;
1.1172.2.56 raeburn 6177: } elsif ($idtype eq 'addcode') {
6178: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 6179: } else {
6180: $newid ++;
6181: }
6182: $idtries ++;
6183: }
6184: if (!exists($inuse{$prefix."\0".$newid})) {
6185: my %new_item = (
6186: $prefix."\0".$newid => $who,
6187: );
6188: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6189: $cdom,$cnum);
6190: if ($putresult ne 'ok') {
6191: undef($newid);
6192: $error = 'error saving new item: '.$putresult;
6193: }
6194: } else {
1.1172.2.56 raeburn 6195: undef($newid);
1.1172.2.13 raeburn 6196: $error = ('error: no unique suffix available for the new item ');
6197: }
6198: # remove lock
6199: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6200: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6201: } else {
6202: $error = "error: could not obtain lockfile\n";
6203: $dellock = 'ok';
1.1172.2.58 raeburn 6204: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6205: $dellock = 'nolock';
6206: }
1.1172.2.13 raeburn 6207: }
6208: return ($newid,$dellock,$error);
6209: }
6210:
1.1172.2.56 raeburn 6211: sub sixnum_code {
6212: my $code;
6213: for (0..6) {
6214: $code .= int( rand(9) );
6215: }
6216: return $code;
6217: }
6218:
1.765 albertel 6219: # -------------------------------------------------- portfolio access checking
6220:
6221: sub portfolio_access {
1.766 albertel 6222: my ($requrl) = @_;
1.765 albertel 6223: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6224: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 6225: if ($result) {
6226: my %setters;
6227: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6228: my ($startblock,$endblock) =
6229: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6230: if ($startblock && $endblock) {
6231: return 'B';
6232: }
6233: } else {
6234: my ($startblock,$endblock) =
6235: &Apache::loncommon::blockcheck(\%setters,'port');
6236: if ($startblock && $endblock) {
6237: return 'B';
6238: }
6239: }
6240: }
1.765 albertel 6241: if ($result eq 'ok') {
1.766 albertel 6242: return 'F';
1.765 albertel 6243: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6244: return 'A';
1.765 albertel 6245: }
1.766 albertel 6246: return '';
1.765 albertel 6247: }
6248:
6249: sub get_portfolio_access {
1.767 albertel 6250: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
6251:
6252: if (!ref($access_hash)) {
6253: my $current_perms = &get_portfile_permissions($udom,$unum);
6254: my %access_controls = &get_access_controls($current_perms,$group,
6255: $file_name);
6256: $access_hash = $access_controls{$file_name};
6257: }
6258:
1.765 albertel 6259: my ($public,$guest,@domains,@users,@courses,@groups);
6260: my $now = time;
6261: if (ref($access_hash) eq 'HASH') {
6262: foreach my $key (keys(%{$access_hash})) {
6263: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6264: if ($start > $now) {
6265: next;
6266: }
6267: if ($end && $end<$now) {
6268: next;
6269: }
6270: if ($scope eq 'public') {
6271: $public = $key;
6272: last;
6273: } elsif ($scope eq 'guest') {
6274: $guest = $key;
6275: } elsif ($scope eq 'domains') {
6276: push(@domains,$key);
6277: } elsif ($scope eq 'users') {
6278: push(@users,$key);
6279: } elsif ($scope eq 'course') {
6280: push(@courses,$key);
6281: } elsif ($scope eq 'group') {
6282: push(@groups,$key);
6283: }
6284: }
6285: if ($public) {
6286: return 'ok';
6287: }
6288: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6289: if ($guest) {
6290: return $guest;
6291: }
6292: } else {
6293: if (@domains > 0) {
6294: foreach my $domkey (@domains) {
6295: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6296: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6297: return 'ok';
6298: }
6299: }
6300: }
6301: }
6302: if (@users > 0) {
6303: foreach my $userkey (@users) {
1.865 raeburn 6304: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6305: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6306: if (ref($item) eq 'HASH') {
6307: if (($item->{'uname'} eq $env{'user.name'}) &&
6308: ($item->{'udom'} eq $env{'user.domain'})) {
6309: return 'ok';
6310: }
6311: }
6312: }
6313: }
1.765 albertel 6314: }
6315: }
6316: my %roleshash;
6317: my @courses_and_groups = @courses;
6318: push(@courses_and_groups,@groups);
6319: if (@courses_and_groups > 0) {
6320: my (%allgroups,%allroles);
6321: my ($start,$end,$role,$sec,$group);
6322: foreach my $envkey (%env) {
1.1060 raeburn 6323: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6324: my $cid = $2.'_'.$3;
6325: if ($1 eq 'gr') {
6326: $group = $4;
6327: $allgroups{$cid}{$group} = $env{$envkey};
6328: } else {
6329: if ($4 eq '') {
6330: $sec = 'none';
6331: } else {
6332: $sec = $4;
6333: }
6334: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6335: }
1.811 albertel 6336: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6337: my $cid = $2.'_'.$3;
6338: if ($4 eq '') {
6339: $sec = 'none';
6340: } else {
6341: $sec = $4;
6342: }
6343: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6344: }
6345: }
6346: if (keys(%allroles) == 0) {
6347: return;
6348: }
6349: foreach my $key (@courses_and_groups) {
6350: my %content = %{$$access_hash{$key}};
6351: my $cnum = $content{'number'};
6352: my $cdom = $content{'domain'};
6353: my $cid = $cdom.'_'.$cnum;
6354: if (!exists($allroles{$cid})) {
6355: next;
6356: }
6357: foreach my $role_id (keys(%{$content{'roles'}})) {
6358: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6359: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6360: my @status = @{$content{'roles'}{$role_id}{'access'}};
6361: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6362: foreach my $role (keys(%{$allroles{$cid}})) {
6363: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6364: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6365: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6366: if (grep/^all$/,@sections) {
6367: return 'ok';
6368: } else {
6369: if (grep/^$sec$/,@sections) {
6370: return 'ok';
6371: }
6372: }
6373: }
6374: }
6375: if (keys(%{$allgroups{$cid}}) == 0) {
6376: if (grep/^none$/,@groups) {
6377: return 'ok';
6378: }
6379: } else {
6380: if (grep/^all$/,@groups) {
6381: return 'ok';
6382: }
6383: foreach my $group (keys(%{$allgroups{$cid}})) {
6384: if (grep/^$group$/,@groups) {
6385: return 'ok';
6386: }
6387: }
6388: }
6389: }
6390: }
6391: }
6392: }
6393: }
6394: if ($guest) {
6395: return $guest;
6396: }
6397: }
6398: }
6399: return;
6400: }
6401:
6402: sub course_group_datechecker {
6403: my ($dates,$now,$status) = @_;
6404: my ($start,$end) = split(/\./,$dates);
6405: if (!$start && !$end) {
6406: return 'ok';
6407: }
6408: if (grep/^active$/,@{$status}) {
6409: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6410: return 'ok';
6411: }
6412: }
6413: if (grep/^previous$/,@{$status}) {
6414: if ($end > $now ) {
6415: return 'ok';
6416: }
6417: }
6418: if (grep/^future$/,@{$status}) {
6419: if ($start > $now) {
6420: return 'ok';
6421: }
6422: }
6423: return;
6424: }
6425:
6426: sub parse_portfolio_url {
6427: my ($url) = @_;
6428:
6429: my ($type,$udom,$unum,$group,$file_name);
6430:
1.823 albertel 6431: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6432: $type = 1;
6433: $udom = $1;
6434: $unum = $2;
6435: $file_name = $3;
1.823 albertel 6436: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6437: $type = 2;
6438: $udom = $1;
6439: $unum = $2;
6440: $group = $3;
6441: $file_name = $3.'/'.$4;
6442: }
6443: if (wantarray) {
6444: return ($type,$udom,$unum,$file_name,$group);
6445: }
6446: return $type;
6447: }
6448:
6449: sub is_portfolio_url {
6450: my ($url) = @_;
6451: return scalar(&parse_portfolio_url($url));
6452: }
6453:
1.798 raeburn 6454: sub is_portfolio_file {
6455: my ($file) = @_;
1.820 raeburn 6456: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6457: return 1;
6458: }
6459: return;
6460: }
6461:
1.976 raeburn 6462: sub usertools_access {
1.1084 raeburn 6463: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6464: my ($access,%tools);
6465: if ($context eq '') {
6466: $context = 'tools';
6467: }
6468: if ($context eq 'requestcourses') {
6469: %tools = (
6470: official => 1,
6471: unofficial => 1,
1.1006 raeburn 6472: community => 1,
1.1172.2.37 raeburn 6473: textbook => 1,
1.985 raeburn 6474: );
1.1172.2.9 raeburn 6475: } elsif ($context eq 'requestauthor') {
6476: %tools = (
6477: requestauthor => 1,
6478: );
1.985 raeburn 6479: } else {
6480: %tools = (
6481: aboutme => 1,
6482: blog => 1,
1.1172.2.6 raeburn 6483: webdav => 1,
1.985 raeburn 6484: portfolio => 1,
6485: );
6486: }
1.976 raeburn 6487: return if (!defined($tools{$tool}));
6488:
1.1172.2.35 raeburn 6489: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6490: $udom = $env{'user.domain'};
6491: $uname = $env{'user.name'};
6492: }
6493:
1.978 raeburn 6494: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6495: if ($action ne 'reload') {
1.985 raeburn 6496: if ($context eq 'requestcourses') {
6497: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 6498: } elsif ($context eq 'requestauthor') {
6499: return $env{'environment.canrequest.author'};
1.985 raeburn 6500: } else {
6501: return $env{'environment.availabletools.'.$tool};
6502: }
6503: }
1.976 raeburn 6504: }
6505:
1.1172.2.9 raeburn 6506: my ($toolstatus,$inststatus,$envkey);
6507: if ($context eq 'requestauthor') {
6508: $envkey = $context;
6509: } else {
6510: $envkey = $context.'.'.$tool;
6511: }
1.976 raeburn 6512:
1.985 raeburn 6513: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6514: ($action ne 'reload')) {
1.1172.2.9 raeburn 6515: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6516: $inststatus = $env{'environment.inststatus'};
6517: } else {
1.1084 raeburn 6518: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 6519: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6520: $inststatus = $userenvref->{'inststatus'};
6521: } else {
1.1172.2.9 raeburn 6522: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6523: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6524: $inststatus = $userenv{'inststatus'};
6525: }
1.976 raeburn 6526: }
6527:
6528: if ($toolstatus ne '') {
6529: if ($toolstatus) {
6530: $access = 1;
6531: } else {
6532: $access = 0;
6533: }
6534: return $access;
6535: }
6536:
1.1084 raeburn 6537: my ($is_adv,%domdef);
6538: if (ref($is_advref) eq 'HASH') {
6539: $is_adv = $is_advref->{'is_adv'};
6540: } else {
6541: $is_adv = &is_advanced_user($udom,$uname);
6542: }
6543: if (ref($domdefref) eq 'HASH') {
6544: %domdef = %{$domdefref};
6545: } else {
6546: %domdef = &get_domain_defaults($udom);
6547: }
1.976 raeburn 6548: if (ref($domdef{$tool}) eq 'HASH') {
6549: if ($is_adv) {
6550: if ($domdef{$tool}{'_LC_adv'} ne '') {
6551: if ($domdef{$tool}{'_LC_adv'}) {
6552: $access = 1;
6553: } else {
6554: $access = 0;
6555: }
6556: return $access;
6557: }
6558: }
6559: if ($inststatus ne '') {
6560: my ($hasaccess,$hasnoaccess);
6561: foreach my $affiliation (split(/:/,$inststatus)) {
6562: if ($domdef{$tool}{$affiliation} ne '') {
6563: if ($domdef{$tool}{$affiliation}) {
6564: $hasaccess = 1;
6565: } else {
6566: $hasnoaccess = 1;
6567: }
6568: }
6569: }
6570: if ($hasaccess || $hasnoaccess) {
6571: if ($hasaccess) {
6572: $access = 1;
6573: } elsif ($hasnoaccess) {
6574: $access = 0;
6575: }
6576: return $access;
6577: }
6578: } else {
6579: if ($domdef{$tool}{'default'} ne '') {
6580: if ($domdef{$tool}{'default'}) {
6581: $access = 1;
6582: } elsif ($domdef{$tool}{'default'} == 0) {
6583: $access = 0;
6584: }
6585: return $access;
6586: }
6587: }
6588: } else {
1.1172.2.6 raeburn 6589: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6590: $access = 1;
6591: } else {
6592: $access = 0;
6593: }
1.976 raeburn 6594: return $access;
6595: }
6596: }
6597:
1.1050 raeburn 6598: sub is_course_owner {
6599: my ($cdom,$cnum,$udom,$uname) = @_;
6600: if (($udom eq '') || ($uname eq '')) {
6601: $udom = $env{'user.domain'};
6602: $uname = $env{'user.name'};
6603: }
6604: unless (($udom eq '') || ($uname eq '')) {
6605: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6606: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6607: return 1;
6608: } else {
6609: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6610: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6611: return 1;
6612: }
6613: }
6614: }
6615: }
6616: return;
6617: }
6618:
1.976 raeburn 6619: sub is_advanced_user {
6620: my ($udom,$uname) = @_;
1.1085 raeburn 6621: if ($udom ne '' && $uname ne '') {
6622: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6623: if (wantarray) {
6624: return ($env{'user.adv'},$env{'user.author'});
6625: } else {
6626: return $env{'user.adv'};
6627: }
1.1085 raeburn 6628: }
6629: }
1.976 raeburn 6630: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6631: my %allroles;
1.1128 raeburn 6632: my ($is_adv,$is_author);
1.976 raeburn 6633: foreach my $role (keys(%roleshash)) {
6634: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6635: my $area = '/'.$tdomain.'/'.$trest;
6636: if ($sec ne '') {
6637: $area .= '/'.$sec;
6638: }
6639: if (($area ne '') && ($trole ne '')) {
6640: my $spec=$trole.'.'.$area;
6641: if ($trole =~ /^cr\//) {
6642: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6643: } elsif ($trole ne 'gr') {
6644: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6645: }
1.1128 raeburn 6646: if ($trole eq 'au') {
6647: $is_author = 1;
6648: }
1.976 raeburn 6649: }
6650: }
6651: foreach my $role (keys(%allroles)) {
6652: last if ($is_adv);
6653: foreach my $item (split(/:/,$allroles{$role})) {
6654: if ($item ne '') {
6655: my ($privilege,$restrictions)=split(/&/,$item);
6656: if ($privilege eq 'adv') {
6657: $is_adv = 1;
6658: last;
6659: }
6660: }
6661: }
6662: }
1.1128 raeburn 6663: if (wantarray) {
6664: return ($is_adv,$is_author);
6665: }
1.976 raeburn 6666: return $is_adv;
6667: }
1.798 raeburn 6668:
1.1035 raeburn 6669: sub check_can_request {
1.1036 raeburn 6670: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6671: my $canreq = 0;
6672: my ($types,$typename) = &Apache::loncommon::course_types();
6673: my @options = ('approval','validate','autolimit');
6674: my $optregex = join('|',@options);
6675: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6676: foreach my $type (@{$types}) {
6677: if (&usertools_access($env{'user.name'},
6678: $env{'user.domain'},
6679: $type,undef,'requestcourses')) {
6680: $canreq ++;
1.1036 raeburn 6681: if (ref($request_domains) eq 'HASH') {
6682: push(@{$request_domains->{$type}},$env{'user.domain'});
6683: }
1.1035 raeburn 6684: if ($dom eq $env{'user.domain'}) {
6685: $can_request->{$type} = 1;
6686: }
6687: }
6688: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6689: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6690: if (@curr > 0) {
1.1036 raeburn 6691: foreach my $item (@curr) {
6692: if (ref($request_domains) eq 'HASH') {
6693: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6694: if ($otherdom ne '') {
6695: if (ref($request_domains->{$type}) eq 'ARRAY') {
6696: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6697: push(@{$request_domains->{$type}},$otherdom);
6698: }
6699: } else {
6700: push(@{$request_domains->{$type}},$otherdom);
6701: }
6702: }
6703: }
6704: }
6705: unless($dom eq $env{'user.domain'}) {
6706: $canreq ++;
1.1035 raeburn 6707: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6708: $can_request->{$type} = 1;
6709: }
6710: }
6711: }
6712: }
6713: }
6714: }
6715: return $canreq;
6716: }
6717:
1.341 www 6718: # ---------------------------------------------- Custom access rule evaluation
6719:
6720: sub customaccess {
6721: my ($priv,$uri)=@_;
1.807 albertel 6722: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6723: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6724: $udom = &LONCAPA::clean_domain($udom);
6725: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6726: my $access=0;
1.800 albertel 6727: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6728: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6729: if ($type eq 'user') {
6730: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6731: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6732: if ($tdom) {
6733: if ($tdom ne $env{'user.domain'}) { next; }
6734: }
1.896 albertel 6735: if ($tuname) {
6736: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6737: }
6738: $access=($effect eq 'allow');
6739: last;
6740: }
6741: } else {
6742: if ($role) {
6743: if ($role ne $urole) { next; }
6744: }
6745: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6746: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6747: if ($tdom) {
6748: if ($tdom ne $udom) { next; }
6749: }
6750: if ($tcrs) {
6751: if ($tcrs ne $ucrs) { next; }
6752: }
6753: if ($tsec) {
6754: if ($tsec ne $usec) { next; }
6755: }
6756: $access=($effect eq 'allow');
6757: last;
6758: }
6759: if ($realm eq '' && $role eq '') {
6760: $access=($effect eq 'allow');
6761: }
1.402 bowersj2 6762: }
1.341 www 6763: }
6764: return $access;
6765: }
6766:
1.103 harris41 6767: # ------------------------------------------------- Check for a user privilege
1.12 www 6768:
6769: sub allowed {
1.1172.2.65 raeburn 6770: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 6771: my $ver_orguri=$uri;
1.439 www 6772: $uri=&deversion($uri);
1.152 www 6773: my $orguri=$uri;
1.52 www 6774: $uri=&declutter($uri);
1.809 raeburn 6775:
1.810 raeburn 6776: if ($priv eq 'evb') {
6777: # Evade communication block restrictions for specified role in a course
6778: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6779: return $1;
6780: } else {
6781: return;
6782: }
6783: }
6784:
1.620 albertel 6785: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6786: # Free bre access to adm and meta resources
1.775 albertel 6787: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6788: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6789: && ($priv eq 'bre')) {
1.14 www 6790: return 'F';
1.159 www 6791: }
6792:
1.545 banghart 6793: # Free bre access to user's own portfolio contents
1.714 raeburn 6794: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6795: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6796: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6797: my %setters;
6798: my ($startblock,$endblock) =
6799: &Apache::loncommon::blockcheck(\%setters,'port');
6800: if ($startblock && $endblock) {
6801: return 'B';
6802: } else {
6803: return 'F';
6804: }
1.545 banghart 6805: }
6806:
1.762 raeburn 6807: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6808: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6809: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6810: if (exists($env{'request.course.id'})) {
6811: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6812: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6813: if (($domain eq $cdom) && ($name eq $cnum)) {
6814: my $courseprivid=$env{'request.course.id'};
6815: $courseprivid=~s/\_/\//;
6816: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6817: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6818: return $1;
1.762 raeburn 6819: } else {
6820: if ($env{'request.course.sec'}) {
6821: $courseprivid.='/'.$env{'request.course.sec'};
6822: }
6823: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6824: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6825: return $2;
6826: }
1.714 raeburn 6827: }
6828: }
6829: }
6830: }
6831:
1.159 www 6832: # Free bre to public access
6833:
6834: if ($priv eq 'bre') {
1.238 www 6835: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6836: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6837: return 'F';
6838: }
1.238 www 6839: if ($copyright eq 'priv') {
6840: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6841: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6842: return '';
6843: }
6844: }
6845: if ($copyright eq 'domain') {
6846: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6847: unless (($env{'user.domain'} eq $1) ||
6848: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6849: return '';
6850: }
1.262 matthew 6851: }
1.620 albertel 6852: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6853: # Library role, so allow browsing of resources in this domain.
6854: return 'F';
1.238 www 6855: }
1.341 www 6856: if ($copyright eq 'custom') {
6857: unless (&customaccess($priv,$uri)) { return ''; }
6858: }
1.14 www 6859: }
1.264 matthew 6860: # Domain coordinator is trying to create a course
1.620 albertel 6861: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6862: # uri is the requested domain in this case.
6863: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6864: # a role of dc for the domain in question.
1.620 albertel 6865: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6866: }
1.29 www 6867:
1.52 www 6868: my $thisallowed='';
6869: my $statecond=0;
6870: my $courseprivid='';
6871:
1.1039 raeburn 6872: my $ownaccess;
1.1043 raeburn 6873: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6874: if (($priv eq 'bro') && ($env{'user.author'})) {
6875: if ($uri eq '') {
6876: $ownaccess = 1;
6877: } else {
6878: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6879: my $udom = $env{'user.domain'};
6880: my $uname = $env{'user.name'};
6881: if ($uri =~ m{^\Q$udom\E/?$}) {
6882: $ownaccess = 1;
1.1040 raeburn 6883: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6884: unless ($uri =~ m{\.\./}) {
6885: $ownaccess = 1;
6886: }
6887: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6888: my $now = time;
6889: if ($uri =~ m{^([^/]+)/?$}) {
6890: my $adom = $1;
6891: foreach my $key (keys(%env)) {
1.1042 raeburn 6892: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6893: my ($start,$end) = split('.',$env{$key});
6894: if (($now >= $start) && (!$end || $end < $now)) {
6895: $ownaccess = 1;
6896: last;
6897: }
6898: }
6899: }
6900: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6901: my $adom = $1;
6902: my $aname = $2;
1.1042 raeburn 6903: foreach my $role ('ca','aa') {
6904: if ($env{"user.role.$role./$adom/$aname"}) {
6905: my ($start,$end) =
6906: split('.',$env{"user.role.$role./$adom/$aname"});
6907: if (($now >= $start) && (!$end || $end < $now)) {
6908: $ownaccess = 1;
6909: last;
6910: }
1.1039 raeburn 6911: }
6912: }
6913: }
6914: }
6915: }
6916: }
6917: }
6918:
1.52 www 6919: # Course
6920:
1.620 albertel 6921: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6922: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6923: $thisallowed.=$1;
6924: }
1.52 www 6925: }
1.29 www 6926:
1.52 www 6927: # Domain
6928:
1.620 albertel 6929: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6930: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6931: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6932: $thisallowed.=$1;
6933: }
1.12 www 6934: }
1.52 www 6935:
1.1141 raeburn 6936: # User who is not author or co-author might still be able to edit
6937: # resource of an author in the domain (e.g., if Domain Coordinator).
6938: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6939: (&allowed('mdc',$env{'request.course.id'}))) {
6940: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6941: $thisallowed.=$1;
6942: }
6943: }
6944:
1.52 www 6945: # Course: uri itself is a course
1.66 www 6946: my $courseuri=$uri;
6947: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6948: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6949:
1.620 albertel 6950: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6951: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6952: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6953: $thisallowed.=$1;
6954: }
1.12 www 6955: }
1.29 www 6956:
1.665 albertel 6957: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6958: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6959: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6960: $thisallowed='';
1.671 raeburn 6961: my ($match)=&is_on_map($uri);
6962: if ($match) {
6963: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6964: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 6965: my $value = $1;
6966: if ($noblockcheck) {
6967: $thisallowed.=$value;
1.1162 raeburn 6968: } else {
1.1172.2.65 raeburn 6969: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6970: if (@blockers > 0) {
6971: $thisallowed = 'B';
6972: } else {
6973: $thisallowed.=$value;
6974: }
1.1162 raeburn 6975: }
1.671 raeburn 6976: }
6977: } else {
1.705 albertel 6978: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6979: if ($refuri) {
6980: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6981: $thisallowed='F';
1.671 raeburn 6982: } else {
6983: $refuri=&declutter($refuri);
6984: my ($match) = &is_on_map($refuri);
6985: if ($match) {
1.1172.2.65 raeburn 6986: if ($noblockcheck) {
1.1162 raeburn 6987: $thisallowed='F';
1.1172.2.65 raeburn 6988: } else {
6989: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6990: if (@blockers > 0) {
6991: $thisallowed = 'B';
6992: } else {
6993: $thisallowed='F';
6994: }
1.1162 raeburn 6995: }
1.671 raeburn 6996: }
1.669 raeburn 6997: }
1.671 raeburn 6998: }
6999: }
1.314 www 7000: }
1.492 albertel 7001:
1.766 albertel 7002: if ($priv eq 'bre'
7003: && $thisallowed ne 'F'
7004: && $thisallowed ne '2'
7005: && &is_portfolio_url($uri)) {
7006: $thisallowed = &portfolio_access($uri);
7007: }
7008:
1.52 www 7009: # Full access at system, domain or course-wide level? Exit.
1.29 www 7010: if ($thisallowed=~/F/) {
7011: return 'F';
7012: }
7013:
1.52 www 7014: # If this is generating or modifying users, exit with special codes
1.29 www 7015:
1.643 www 7016: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7017: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7018: my ($audom,$auname)=split('/',$uri);
1.643 www 7019: # no author name given, so this just checks on the general right to make a co-author in this domain
7020: unless ($auname) { return $thisallowed; }
7021: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7022: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7023: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7024: ($audom ne $env{'request.role.domain'}))) { return ''; }
7025: }
1.52 www 7026: return $thisallowed;
7027: }
7028: #
1.103 harris41 7029: # Gathered so far: system, domain and course wide privileges
1.52 www 7030: #
7031: # Course: See if uri or referer is an individual resource that is part of
7032: # the course
7033:
1.620 albertel 7034: if ($env{'request.course.id'}) {
1.232 www 7035:
1.620 albertel 7036: $courseprivid=$env{'request.course.id'};
7037: if ($env{'request.course.sec'}) {
7038: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7039: }
7040: $courseprivid=~s/\_/\//;
7041: my $checkreferer=1;
1.232 www 7042: my ($match,$cond)=&is_on_map($uri);
7043: if ($match) {
7044: $statecond=$cond;
1.620 albertel 7045: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7046: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7047: my $value = $1;
7048: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7049: if ($noblockcheck) {
1.1162 raeburn 7050: $thisallowed.=$value;
1.1172.2.65 raeburn 7051: } else {
7052: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7053: if (@blockers > 0) {
7054: $thisallowed = 'B';
7055: } else {
7056: $thisallowed.=$value;
7057: }
1.1162 raeburn 7058: }
7059: } else {
7060: $thisallowed.=$value;
7061: }
1.52 www 7062: $checkreferer=0;
7063: }
1.29 www 7064: }
1.83 www 7065:
1.148 www 7066: if ($checkreferer) {
1.620 albertel 7067: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7068: unless ($refuri) {
1.800 albertel 7069: foreach my $key (keys(%env)) {
7070: if ($key=~/^httpref\..*\*/) {
7071: my $pattern=$key;
1.156 www 7072: $pattern=~s/^httpref\.\/res\///;
1.148 www 7073: $pattern=~s/\*/\[\^\/\]\+/g;
7074: $pattern=~s/\//\\\//g;
1.152 www 7075: if ($orguri=~/$pattern/) {
1.800 albertel 7076: $refuri=$env{$key};
1.148 www 7077: }
7078: }
1.191 harris41 7079: }
1.148 www 7080: }
1.232 www 7081:
1.148 www 7082: if ($refuri) {
1.152 www 7083: $refuri=&declutter($refuri);
1.232 www 7084: my ($match,$cond)=&is_on_map($refuri);
7085: if ($match) {
7086: my $refstatecond=$cond;
1.620 albertel 7087: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7088: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7089: my $value = $1;
7090: if ($priv eq 'bre') {
1.1172.2.65 raeburn 7091: if ($noblockcheck) {
1.1162 raeburn 7092: $thisallowed.=$value;
1.1172.2.65 raeburn 7093: } else {
7094: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7095: if (@blockers > 0) {
7096: $thisallowed = 'B';
7097: } else {
7098: $thisallowed.=$value;
7099: }
1.1162 raeburn 7100: }
7101: } else {
7102: $thisallowed.=$value;
7103: }
1.53 www 7104: $uri=$refuri;
7105: $statecond=$refstatecond;
1.52 www 7106: }
7107: }
1.148 www 7108: }
1.29 www 7109: }
1.52 www 7110: }
1.29 www 7111:
1.52 www 7112: #
1.103 harris41 7113: # Gathered now: all privileges that could apply, and condition number
1.52 www 7114: #
7115: #
7116: # Full or no access?
7117: #
1.29 www 7118:
1.52 www 7119: if ($thisallowed=~/F/) {
7120: return 'F';
7121: }
1.29 www 7122:
1.52 www 7123: unless ($thisallowed) {
7124: return '';
7125: }
1.29 www 7126:
1.52 www 7127: # Restrictions exist, deal with them
7128: #
7129: # C:according to course preferences
7130: # R:according to resource settings
7131: # L:unless locked
7132: # X:according to user session state
7133: #
7134:
7135: # Possibly locked functionality, check all courses
1.54 www 7136: # Locks might take effect only after 10 minutes cache expiration for other
7137: # courses, and 2 minutes for current course
1.52 www 7138:
7139: my $envkey;
7140: if ($thisallowed=~/L/) {
1.1000 raeburn 7141: foreach $envkey (keys(%env)) {
1.54 www 7142: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7143: my $courseid=$2;
7144: my $roleid=$1.'.'.$2;
1.92 www 7145: $courseid=~s/^\///;
1.54 www 7146: my $expiretime=600;
1.620 albertel 7147: if ($env{'request.role'} eq $roleid) {
1.54 www 7148: $expiretime=120;
7149: }
7150: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7151: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7152: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7153: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7154: }
1.620 albertel 7155: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7156: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7157: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7158: &log($env{'user.domain'},$env{'user.name'},
7159: $env{'user.home'},
1.57 www 7160: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7161: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7162: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7163: return '';
7164: }
7165: }
1.620 albertel 7166: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7167: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7168: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7169: &log($env{'user.domain'},$env{'user.name'},
7170: $env{'user.home'},
1.57 www 7171: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7172: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7173: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7174: return '';
7175: }
7176: }
7177: }
1.29 www 7178: }
1.52 www 7179: }
7180:
7181: #
7182: # Rest of the restrictions depend on selected course
7183: #
7184:
1.620 albertel 7185: unless ($env{'request.course.id'}) {
1.766 albertel 7186: if ($thisallowed eq 'A') {
7187: return 'A';
1.814 raeburn 7188: } elsif ($thisallowed eq 'B') {
7189: return 'B';
1.766 albertel 7190: } else {
7191: return '1';
7192: }
1.52 www 7193: }
1.29 www 7194:
1.52 www 7195: #
7196: # Now user is definitely in a course
7197: #
1.53 www 7198:
7199:
7200: # Course preferences
7201:
7202: if ($thisallowed=~/C/) {
1.620 albertel 7203: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7204: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7205: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7206: =~/\Q$rolecode\E/) {
1.1103 raeburn 7207: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7208: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7209: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7210: $env{'request.course.id'});
7211: }
1.237 www 7212: return '';
7213: }
7214:
1.620 albertel 7215: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7216: =~/\Q$unamedom\E/) {
1.1103 raeburn 7217: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7218: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7219: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7220: $env{'request.course.id'});
7221: }
1.54 www 7222: return '';
7223: }
1.53 www 7224: }
7225:
7226: # Resource preferences
7227:
7228: if ($thisallowed=~/R/) {
1.620 albertel 7229: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7230: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7231: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7232: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7233: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7234: }
7235: return '';
1.54 www 7236: }
1.53 www 7237: }
1.30 www 7238:
1.246 www 7239: # Restricted by state or randomout?
1.30 www 7240:
1.52 www 7241: if ($thisallowed=~/X/) {
1.620 albertel 7242: if ($env{'acc.randomout'}) {
1.579 albertel 7243: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7244: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7245: return '';
7246: }
1.247 www 7247: }
7248: if (&condval($statecond)) {
1.52 www 7249: return '2';
7250: } else {
7251: return '';
7252: }
7253: }
1.30 www 7254:
1.766 albertel 7255: if ($thisallowed eq 'A') {
7256: return 'A';
1.814 raeburn 7257: } elsif ($thisallowed eq 'B') {
7258: return 'B';
1.766 albertel 7259: }
1.52 www 7260: return 'F';
1.232 www 7261: }
1.1162 raeburn 7262:
1.1172.2.13 raeburn 7263: # ------------------------------------------- Check construction space access
7264:
7265: sub constructaccess {
7266: my ($url,$setpriv)=@_;
7267:
7268: # We do not allow editing of previous versions of files
7269: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7270:
7271: # Get username and domain from URL
7272: my ($ownername,$ownerdomain,$ownerhome);
7273:
7274: ($ownerdomain,$ownername) =
7275: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7276:
7277: # The URL does not really point to any authorspace, forget it
7278: unless (($ownername) && ($ownerdomain)) { return ''; }
7279:
7280: # Now we need to see if the user has access to the authorspace of
7281: # $ownername at $ownerdomain
7282:
7283: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7284: # Real author for this?
7285: $ownerhome = $env{'user.home'};
7286: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7287: return ($ownername,$ownerdomain,$ownerhome);
7288: }
7289: } else {
7290: # Co-author for this?
7291: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7292: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7293: $ownerhome = &homeserver($ownername,$ownerdomain);
7294: return ($ownername,$ownerdomain,$ownerhome);
7295: }
7296: }
7297:
7298: # We don't have any access right now. If we are not possibly going to do anything about this,
7299: # we might as well leave
7300: unless ($setpriv) { return ''; }
7301:
7302: # Backdoor access?
7303: my $allowed=&allowed('eco',$ownerdomain);
7304: # Nope
7305: unless ($allowed) { return ''; }
7306: # Looks like we may have access, but could be locked by the owner of the construction space
7307: if ($allowed eq 'U') {
7308: my %blocked=&get('environment',['domcoord.author'],
7309: $ownerdomain,$ownername);
7310: # Is blocked by owner
7311: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7312: }
7313: if (($allowed eq 'F') || ($allowed eq 'U')) {
7314: # Grant temporary access
7315: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 7316: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 7317: if (!$update) { $update = $then; }
7318: my $refresh=$env{'user.refresh.time'};
7319: if (!$refresh) { $refresh = $update; }
7320: my $now = time;
7321: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7322: $now,'ca','constructaccess');
7323: $ownerhome = &homeserver($ownername,$ownerdomain);
7324: return($ownername,$ownerdomain,$ownerhome);
7325: }
7326: # No business here
7327: return '';
7328: }
7329:
1.1172.2.66 raeburn 7330: # ----------------------------------------------------------- Content Blocking
7331:
7332: {
7333: # Caches for faster Course Contents display where content blocking
7334: # is in operation (i.e., interval param set) for timed quiz.
7335: #
7336: # User for whom data are being temporarily cached.
7337: my $cacheduser='';
7338: # Cached blockers for this user (a hash of blocking items).
7339: my %cachedblockers=();
7340: # When the data were last cached.
7341: my $cachedlast='';
7342:
7343: sub load_all_blockers {
7344: my ($uname,$udom,$blocks)=@_;
7345: if (($uname ne '') && ($udom ne '')) {
7346: if (($cacheduser eq $uname.':'.$udom) &&
7347: (abs($cachedlast-time)<5)) {
7348: return;
7349: }
7350: }
7351: $cachedlast=time;
7352: $cacheduser=$uname.':'.$udom;
7353: %cachedblockers = &get_commblock_resources($blocks);
7354: }
7355:
1.1162 raeburn 7356: sub get_comm_blocks {
7357: my ($cdom,$cnum) = @_;
7358: if ($cdom eq '' || $cnum eq '') {
7359: return unless ($env{'request.course.id'});
7360: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7361: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7362: }
7363: my %commblocks;
7364: my $hashid=$cdom.'_'.$cnum;
7365: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7366: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7367: %commblocks = %{$blocksref};
7368: } else {
7369: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7370: my $cachetime = 600;
7371: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7372: }
7373: return %commblocks;
7374: }
7375:
1.1172.2.66 raeburn 7376: sub get_commblock_resources {
7377: my ($blocks) = @_;
7378: my %blockers = ();
7379: return %blockers unless ($env{'request.course.id'});
7380: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7381: my %commblocks;
7382: if (ref($blocks) eq 'HASH') {
7383: %commblocks = %{$blocks};
7384: } else {
7385: %commblocks = &get_comm_blocks();
7386: }
1.1172.2.66 raeburn 7387: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 7388: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 7389: return %blockers unless (ref($navmap));
7390: my $now = time;
1.1162 raeburn 7391: foreach my $block (keys(%commblocks)) {
7392: if ($block =~ /^(\d+)____(\d+)$/) {
7393: my ($start,$end) = ($1,$2);
7394: if ($start <= $now && $end >= $now) {
7395: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7396: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7397: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 7398: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7399: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7400: }
7401: }
7402: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 7403: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7404: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7405: }
7406: }
7407: }
7408: }
7409: }
7410: } elsif ($block =~ /^firstaccess____(.+)$/) {
7411: my $item = $1;
1.1163 raeburn 7412: my @to_test;
1.1162 raeburn 7413: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7414: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66 raeburn 7415: my @interval;
7416: my $type = 'map';
7417: if ($item eq 'course') {
7418: $type = 'course';
7419: @interval=&EXT("resource.0.interval");
7420: } else {
7421: if ($item =~ /___\d+___/) {
7422: $type = 'resource';
7423: @interval=&EXT("resource.0.interval",$item);
7424: if (ref($navmap)) {
7425: my $res = $navmap->getBySymb($item);
7426: push(@to_test,$res);
7427: }
1.1162 raeburn 7428: } else {
1.1172.2.66 raeburn 7429: my $mapsymb = &symbread($item,1);
7430: if ($mapsymb) {
7431: if (ref($navmap)) {
7432: my $mapres = $navmap->getBySymb($mapsymb);
7433: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7434: foreach my $res (@to_test) {
7435: my $symb = $res->symb();
7436: next if ($symb eq $mapsymb);
7437: if ($symb ne '') {
7438: @interval=&EXT("resource.0.interval",$symb);
7439: if ($interval[1] eq 'map') {
7440: last;
1.1162 raeburn 7441: }
7442: }
7443: }
7444: }
7445: }
7446: }
1.1172.2.66 raeburn 7447: }
7448: if ($interval[0] =~ /^\d+$/) {
7449: my $first_access;
7450: if ($type eq 'resource') {
7451: $first_access=&get_first_access($interval[1],$item);
7452: } elsif ($type eq 'map') {
7453: $first_access=&get_first_access($interval[1],undef,$item);
7454: } else {
7455: $first_access=&get_first_access($interval[1]);
7456: }
7457: if ($first_access) {
7458: my $timesup = $first_access+$interval[0];
7459: if ($timesup > $now) {
7460: my $activeblock;
7461: foreach my $res (@to_test) {
7462: if ($res->answerable()) {
7463: $activeblock = 1;
7464: last;
7465: }
7466: }
7467: if ($activeblock) {
7468: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7469: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7470: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7471: }
7472: }
7473: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7474: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7475: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7476: }
1.1162 raeburn 7477: }
7478: }
7479: }
7480: }
7481: }
7482: }
7483: }
7484: }
7485: }
1.1172.2.66 raeburn 7486: return %blockers;
1.1162 raeburn 7487: }
7488:
1.1172.2.66 raeburn 7489: sub has_comm_blocking {
7490: my ($priv,$symb,$uri,$blocks) = @_;
7491: my @blockers;
7492: return unless ($env{'request.course.id'});
7493: return unless ($priv eq 'bre');
7494: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7495: return if ($env{'request.state'} eq 'construct');
7496: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7497: return unless (keys(%cachedblockers) > 0);
7498: my (%possibles,@symbs);
7499: if (!$symb) {
7500: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7501: }
1.1172.2.66 raeburn 7502: if ($symb) {
7503: @symbs = ($symb);
7504: } elsif (keys(%possibles)) {
7505: @symbs = keys(%possibles);
7506: }
7507: my $noblock;
7508: foreach my $symb (@symbs) {
7509: last if ($noblock);
7510: my ($map,$resid,$resurl)=&decode_symb($symb);
7511: foreach my $block (keys(%cachedblockers)) {
7512: if ($block =~ /^firstaccess____(.+)$/) {
7513: my $item = $1;
7514: if (($item eq $map) || ($item eq $symb)) {
7515: $noblock = 1;
7516: last;
7517: }
1.1162 raeburn 7518: }
1.1172.2.66 raeburn 7519: if (ref($cachedblockers{$block}) eq 'HASH') {
7520: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7521: if ($cachedblockers{$block}{'resources'}{$symb}) {
7522: unless (grep(/^\Q$block\E$/,@blockers)) {
7523: push(@blockers,$block);
7524: }
7525: }
7526: }
7527: }
7528: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7529: if ($cachedblockers{$block}{'maps'}{$map}) {
7530: unless (grep(/^\Q$block\E$/,@blockers)) {
7531: push(@blockers,$block);
7532: }
7533: }
1.1162 raeburn 7534: }
7535: }
7536: }
1.1172.2.66 raeburn 7537: return if ($noblock);
7538: return @blockers;
7539: }
1.1162 raeburn 7540: }
7541:
1.1172.2.66 raeburn 7542: # -------------------------------- Deversion and split uri into path an filename
7543:
1.1133 foxr 7544: #
1.1172.2.66 raeburn 7545: # Removes the version from a URI and
1.1133 foxr 7546: # splits it in to its filename and path to the filename.
7547: # Seems like File::Basename could have done this more clearly.
7548: # Parameters:
7549: # $uri - input URI
7550: # Returns:
7551: # Two element list consisting of
7552: # $pathname - the URI up to and excluding the trailing /
7553: # $filename - The part of the URI following the last /
7554: # NOTE:
7555: # Another realization of this is simply:
7556: # use File::Basename;
7557: # ...
7558: # $uri = shift;
7559: # $filename = basename($uri);
7560: # $path = dirname($uri);
7561: # return ($filename, $path);
7562: #
7563: # The implementation below is probably faster however.
7564: #
1.710 albertel 7565: sub split_uri_for_cond {
7566: my $uri=&deversion(&declutter(shift));
7567: my @uriparts=split(/\//,$uri);
7568: my $filename=pop(@uriparts);
7569: my $pathname=join('/',@uriparts);
7570: return ($pathname,$filename);
7571: }
1.232 www 7572: # --------------------------------------------------- Is a resource on the map?
7573:
7574: sub is_on_map {
1.710 albertel 7575: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7576: #Trying to find the conditional for the file
1.620 albertel 7577: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7578: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7579: if ($match) {
1.289 bowersj2 7580: return (1,$1);
7581: } else {
1.434 www 7582: return (0,0);
1.289 bowersj2 7583: }
1.12 www 7584: }
7585:
1.427 www 7586: # --------------------------------------------------------- Get symb from alias
7587:
7588: sub get_symb_from_alias {
7589: my $symb=shift;
7590: my ($map,$resid,$url)=&decode_symb($symb);
7591: # Already is a symb
7592: if ($url) { return $symb; }
7593: # Must be an alias
7594: my $aliassymb='';
7595: my %bighash;
1.620 albertel 7596: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7597: &GDBM_READER(),0640)) {
7598: my $rid=$bighash{'mapalias_'.$symb};
7599: if ($rid) {
7600: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7601: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7602: $resid,$bighash{'src_'.$rid});
1.427 www 7603: }
7604: untie %bighash;
7605: }
7606: return $aliassymb;
7607: }
7608:
1.12 www 7609: # ----------------------------------------------------------------- Define Role
7610:
7611: sub definerole {
7612: if (allowed('mcr','/')) {
7613: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7614: foreach my $role (split(':',$sysrole)) {
7615: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7616: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7617: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7618: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7619: return "refused:s:$crole&$cqual";
7620: }
7621: }
1.191 harris41 7622: }
1.800 albertel 7623: foreach my $role (split(':',$domrole)) {
7624: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7625: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7626: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7627: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7628: return "refused:d:$crole&$cqual";
7629: }
7630: }
1.191 harris41 7631: }
1.800 albertel 7632: foreach my $role (split(':',$courole)) {
7633: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7634: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7635: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7636: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7637: return "refused:c:$crole&$cqual";
7638: }
7639: }
1.191 harris41 7640: }
1.620 albertel 7641: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7642: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7643: "rolesdef_$rolename=".
7644: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7645: return reply($command,$env{'user.home'});
1.12 www 7646: } else {
7647: return 'refused';
7648: }
1.105 harris41 7649: }
7650:
7651: # ---------------- Make a metadata query against the network of library servers
7652:
7653: sub metadata_query {
1.1172.2.33 raeburn 7654: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7655: my %rhash;
1.845 albertel 7656: my %libserv = &all_library();
1.244 matthew 7657: my @server_list = (defined($server_array) ? @$server_array
7658: : keys(%libserv) );
7659: for my $server (@server_list) {
1.1172.2.33 raeburn 7660: my $domains = '';
7661: if (ref($domains_hash) eq 'HASH') {
7662: $domains = $domains_hash->{$server};
7663: }
1.118 harris41 7664: unless ($custom or $customshow) {
1.1172.2.33 raeburn 7665: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7666: $rhash{$server}=$reply;
7667: }
7668: else {
7669: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 7670: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7671: $server);
7672: $rhash{$server}=$reply;
7673: }
1.112 harris41 7674: }
1.118 harris41 7675: return \%rhash;
1.240 www 7676: }
7677:
7678: # ----------------------------------------- Send log queries and wait for reply
7679:
7680: sub log_query {
7681: my ($uname,$udom,$query,%filters)=@_;
7682: my $uhome=&homeserver($uname,$udom);
7683: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7684: my $uhost=&hostname($uhome);
1.800 albertel 7685: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7686: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7687: $uhome);
1.479 albertel 7688: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7689: return get_query_reply($queryid);
7690: }
7691:
1.818 raeburn 7692: # -------------------------- Update MySQL table for portfolio file
7693:
7694: sub update_portfolio_table {
1.821 raeburn 7695: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7696: if ($group ne '') {
7697: $file_name =~s /^\Q$group\E//;
7698: }
1.818 raeburn 7699: my $homeserver = &homeserver($uname,$udom);
7700: my $queryid=
1.821 raeburn 7701: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7702: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7703: my $reply = &get_query_reply($queryid);
7704: return $reply;
7705: }
7706:
1.899 raeburn 7707: # -------------------------- Update MySQL allusers table
7708:
7709: sub update_allusers_table {
7710: my ($uname,$udom,$names) = @_;
7711: my $homeserver = &homeserver($uname,$udom);
7712: my $queryid=
7713: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7714: 'lastname='.&escape($names->{'lastname'}).'%%'.
7715: 'firstname='.&escape($names->{'firstname'}).'%%'.
7716: 'middlename='.&escape($names->{'middlename'}).'%%'.
7717: 'generation='.&escape($names->{'generation'}).'%%'.
7718: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7719: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7720: return;
1.899 raeburn 7721: }
7722:
1.508 raeburn 7723: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7724:
7725: sub fetch_enrollment_query {
1.511 raeburn 7726: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7727: my $homeserver;
1.547 raeburn 7728: my $maxtries = 1;
1.508 raeburn 7729: if ($context eq 'automated') {
7730: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7731: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7732: } else {
7733: $homeserver = &homeserver($cnum,$dom);
7734: }
1.838 albertel 7735: my $host=&hostname($homeserver);
1.506 raeburn 7736: my $cmd = '';
1.1000 raeburn 7737: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7738: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7739: }
7740: $cmd =~ s/%%$//;
7741: $cmd = &escape($cmd);
7742: my $query = 'fetchenrollment';
1.620 albertel 7743: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7744: unless ($queryid=~/^\Q$host\E\_/) {
7745: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7746: return 'error: '.$queryid;
7747: }
1.506 raeburn 7748: my $reply = &get_query_reply($queryid);
1.547 raeburn 7749: my $tries = 1;
7750: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7751: $reply = &get_query_reply($queryid);
7752: $tries ++;
7753: }
1.526 raeburn 7754: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7755: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7756: } else {
1.901 albertel 7757: my @responses = split(/:/,$reply);
1.515 raeburn 7758: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7759: foreach my $line (@responses) {
7760: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7761: $$replyref{$key} = $value;
7762: }
7763: } else {
1.1117 foxr 7764: my $pathname = LONCAPA::tempdir();
1.800 albertel 7765: foreach my $line (@responses) {
7766: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7767: $$replyref{$key} = $value;
7768: if ($value > 0) {
1.800 albertel 7769: foreach my $item (@{$$affiliatesref{$key}}) {
7770: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7771: my $destname = $pathname.'/'.$filename;
7772: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7773: if ($xml_classlist =~ /^error/) {
7774: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7775: } else {
1.506 raeburn 7776: if ( open(FILE,">$destname") ) {
7777: print FILE &unescape($xml_classlist);
7778: close(FILE);
1.526 raeburn 7779: } else {
7780: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7781: }
7782: }
7783: }
7784: }
7785: }
7786: }
7787: return 'ok';
7788: }
7789: return 'error';
7790: }
7791:
1.242 www 7792: sub get_query_reply {
7793: my $queryid=shift;
1.1117 foxr 7794: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7795: my $reply='';
7796: for (1..100) {
7797: sleep 2;
7798: if (-e $replyfile.'.end') {
1.448 albertel 7799: if (open(my $fh,$replyfile)) {
1.904 albertel 7800: $reply = join('',<$fh>);
7801: close($fh);
1.240 www 7802: } else { return 'error: reply_file_error'; }
1.242 www 7803: return &unescape($reply);
7804: }
1.240 www 7805: }
1.242 www 7806: return 'timeout:'.$queryid;
1.240 www 7807: }
7808:
7809: sub courselog_query {
1.241 www 7810: #
7811: # possible filters:
7812: # url: url or symb
7813: # username
7814: # domain
7815: # action: view, submit, grade
7816: # start: timestamp
7817: # end: timestamp
7818: #
1.240 www 7819: my (%filters)=@_;
1.620 albertel 7820: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7821: if ($filters{'url'}) {
7822: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7823: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7824: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7825: }
1.620 albertel 7826: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7827: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7828: return &log_query($cname,$cdom,'courselog',%filters);
7829: }
7830:
7831: sub userlog_query {
1.858 raeburn 7832: #
7833: # possible filters:
7834: # action: log check role
7835: # start: timestamp
7836: # end: timestamp
7837: #
1.240 www 7838: my ($uname,$udom,%filters)=@_;
7839: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7840: }
7841:
1.506 raeburn 7842: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7843:
7844: sub auto_run {
1.508 raeburn 7845: my ($cnum,$cdom) = @_;
1.876 raeburn 7846: my $response = 0;
7847: my $settings;
7848: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7849: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7850: $settings = $domconfig{'autoenroll'};
7851: if ($settings->{'run'} eq '1') {
7852: $response = 1;
7853: }
7854: } else {
1.934 raeburn 7855: my $homeserver;
7856: if (&is_course($cdom,$cnum)) {
7857: $homeserver = &homeserver($cnum,$cdom);
7858: } else {
7859: $homeserver = &domain($cdom,'primary');
7860: }
7861: if ($homeserver ne 'no_host') {
7862: $response = &reply('autorun:'.$cdom,$homeserver);
7863: }
1.876 raeburn 7864: }
1.506 raeburn 7865: return $response;
7866: }
1.776 albertel 7867:
1.506 raeburn 7868: sub auto_get_sections {
1.508 raeburn 7869: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7870: my $homeserver;
7871: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7872: $homeserver = &homeserver($cnum,$cdom);
7873: }
7874: if (!defined($homeserver)) {
7875: if ($cdom =~ /^$match_domain$/) {
7876: $homeserver = &domain($cdom,'primary');
7877: }
7878: }
7879: my @secs;
7880: if (defined($homeserver)) {
7881: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7882: unless ($response eq 'refused') {
7883: @secs = split(/:/,$response);
7884: }
1.506 raeburn 7885: }
7886: return @secs;
7887: }
1.776 albertel 7888:
1.506 raeburn 7889: sub auto_new_course {
1.1099 raeburn 7890: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7891: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7892: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7893: return $response;
7894: }
1.776 albertel 7895:
1.506 raeburn 7896: sub auto_validate_courseID {
1.508 raeburn 7897: my ($cnum,$cdom,$inst_course_id) = @_;
7898: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7899: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7900: return $response;
7901: }
1.776 albertel 7902:
1.1007 raeburn 7903: sub auto_validate_instcode {
1.1020 raeburn 7904: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7905: my ($homeserver,$response);
7906: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7907: $homeserver = &homeserver($cnum,$cdom);
7908: }
7909: if (!defined($homeserver)) {
7910: if ($cdom =~ /^$match_domain$/) {
7911: $homeserver = &domain($cdom,'primary');
7912: }
7913: }
1.1065 raeburn 7914: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7915: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 7916: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7917: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7918: }
7919:
1.506 raeburn 7920: sub auto_create_password {
1.873 raeburn 7921: my ($cnum,$cdom,$authparam,$udom) = @_;
7922: my ($homeserver,$response);
1.506 raeburn 7923: my $create_passwd = 0;
7924: my $authchk = '';
1.873 raeburn 7925: if ($udom =~ /^$match_domain$/) {
7926: $homeserver = &domain($udom,'primary');
7927: }
7928: if ($homeserver eq '') {
7929: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7930: $homeserver = &homeserver($cnum,$cdom);
7931: }
7932: }
7933: if ($homeserver eq '') {
7934: $authchk = 'nodomain';
1.506 raeburn 7935: } else {
1.873 raeburn 7936: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7937: if ($response eq 'refused') {
7938: $authchk = 'refused';
7939: } else {
1.901 albertel 7940: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7941: }
1.506 raeburn 7942: }
7943: return ($authparam,$create_passwd,$authchk);
7944: }
7945:
1.706 raeburn 7946: sub auto_photo_permission {
7947: my ($cnum,$cdom,$students) = @_;
7948: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7949: my ($outcome,$perm_reqd,$conditions) =
7950: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7951: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7952: return (undef,undef);
7953: }
1.706 raeburn 7954: return ($outcome,$perm_reqd,$conditions);
7955: }
7956:
7957: sub auto_checkphotos {
7958: my ($uname,$udom,$pid) = @_;
7959: my $homeserver = &homeserver($uname,$udom);
7960: my ($result,$resulttype);
7961: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7962: &escape($uname).':'.&escape($pid),
7963: $homeserver));
1.709 albertel 7964: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7965: return (undef,undef);
7966: }
1.706 raeburn 7967: if ($outcome) {
7968: ($result,$resulttype) = split(/:/,$outcome);
7969: }
7970: return ($result,$resulttype);
7971: }
7972:
7973: sub auto_photochoice {
7974: my ($cnum,$cdom) = @_;
7975: my $homeserver = &homeserver($cnum,$cdom);
7976: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7977: &escape($cdom),
7978: $homeserver)));
1.709 albertel 7979: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7980: return (undef,undef);
7981: }
1.706 raeburn 7982: return ($update,$comment);
7983: }
7984:
7985: sub auto_photoupdate {
7986: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7987: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7988: my $host=&hostname($homeserver);
1.706 raeburn 7989: my $cmd = '';
7990: my $maxtries = 1;
1.800 albertel 7991: foreach my $affiliate (keys(%{$affiliatesref})) {
7992: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7993: }
7994: $cmd =~ s/%%$//;
7995: $cmd = &escape($cmd);
7996: my $query = 'institutionalphotos';
7997: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7998: unless ($queryid=~/^\Q$host\E\_/) {
7999: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8000: return 'error: '.$queryid;
8001: }
8002: my $reply = &get_query_reply($queryid);
8003: my $tries = 1;
8004: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8005: $reply = &get_query_reply($queryid);
8006: $tries ++;
8007: }
8008: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8009: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8010: } else {
8011: my @responses = split(/:/,$reply);
8012: my $outcome = shift(@responses);
8013: foreach my $item (@responses) {
8014: my ($key,$value) = split(/=/,$item);
8015: $$photo{$key} = $value;
8016: }
8017: return $outcome;
8018: }
8019: return 'error';
8020: }
8021:
1.521 raeburn 8022: sub auto_instcode_format {
1.793 albertel 8023: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8024: $cat_order) = @_;
1.521 raeburn 8025: my $courses = '';
1.772 raeburn 8026: my @homeservers;
1.521 raeburn 8027: if ($caller eq 'global') {
1.841 albertel 8028: my %servers = &get_servers($codedom,'library');
8029: foreach my $tryserver (keys(%servers)) {
8030: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8031: push(@homeservers,$tryserver);
8032: }
1.584 raeburn 8033: }
1.1022 raeburn 8034: } elsif ($caller eq 'requests') {
8035: if ($codedom =~ /^$match_domain$/) {
8036: my $chome = &domain($codedom,'primary');
8037: unless ($chome eq 'no_host') {
8038: push(@homeservers,$chome);
8039: }
8040: }
1.521 raeburn 8041: } else {
1.772 raeburn 8042: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8043: }
1.793 albertel 8044: foreach my $code (keys(%{$instcodes})) {
8045: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8046: }
8047: chop($courses);
1.772 raeburn 8048: my $ok_response = 0;
8049: my $response;
8050: while (@homeservers > 0 && $ok_response == 0) {
8051: my $server = shift(@homeservers);
8052: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8053: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8054: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8055: split(/:/,$response);
1.772 raeburn 8056: %{$codes} = (%{$codes},&str2hash($codes_str));
8057: push(@{$codetitles},&str2array($codetitles_str));
8058: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8059: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8060: $ok_response = 1;
8061: }
8062: }
8063: if ($ok_response) {
1.521 raeburn 8064: return 'ok';
1.772 raeburn 8065: } else {
8066: return $response;
1.521 raeburn 8067: }
8068: }
8069:
1.792 raeburn 8070: sub auto_instcode_defaults {
8071: my ($domain,$returnhash,$code_order) = @_;
8072: my @homeservers;
1.841 albertel 8073:
8074: my %servers = &get_servers($domain,'library');
8075: foreach my $tryserver (keys(%servers)) {
8076: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8077: push(@homeservers,$tryserver);
8078: }
1.792 raeburn 8079: }
1.841 albertel 8080:
1.792 raeburn 8081: my $response;
1.841 albertel 8082: foreach my $server (@homeservers) {
1.792 raeburn 8083: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8084: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8085:
8086: foreach my $pair (split(/\&/,$response)) {
8087: my ($name,$value)=split(/\=/,$pair);
8088: if ($name eq 'code_order') {
8089: @{$code_order} = split(/\&/,&unescape($value));
8090: } else {
8091: $returnhash->{&unescape($name)}=&unescape($value);
8092: }
8093: }
8094: return 'ok';
1.792 raeburn 8095: }
1.841 albertel 8096:
8097: return $response;
1.1003 raeburn 8098: }
8099:
8100: sub auto_possible_instcodes {
1.1007 raeburn 8101: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8102: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8103: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8104: return;
8105: }
1.1003 raeburn 8106: my (@homeservers,$uhome);
8107: if (defined(&domain($domain,'primary'))) {
8108: $uhome=&domain($domain,'primary');
8109: push(@homeservers,&domain($domain,'primary'));
8110: } else {
8111: my %servers = &get_servers($domain,'library');
8112: foreach my $tryserver (keys(%servers)) {
8113: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8114: push(@homeservers,$tryserver);
8115: }
8116: }
8117: }
8118: my $response;
8119: foreach my $server (@homeservers) {
8120: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8121: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8122: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8123: split(':',$response);
8124: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8125: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8126: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8127: my ($name,$value)=split('=',$item);
8128: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8129: }
8130: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8131: my ($name,$value)=split('=',$item);
8132: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8133: }
8134: return 'ok';
8135: }
8136: return $response;
8137: }
1.792 raeburn 8138:
1.1010 raeburn 8139: sub auto_courserequest_checks {
8140: my ($dom) = @_;
1.1020 raeburn 8141: my ($homeserver,%validations);
8142: if ($dom =~ /^$match_domain$/) {
8143: $homeserver = &domain($dom,'primary');
8144: }
8145: unless ($homeserver eq 'no_host') {
8146: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8147: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8148: my @items = split(/&/,$response);
8149: foreach my $item (@items) {
8150: my ($key,$value) = split('=',$item);
8151: $validations{&unescape($key)} = &thaw_unescape($value);
8152: }
8153: }
8154: }
1.1010 raeburn 8155: return %validations;
8156: }
8157:
1.1020 raeburn 8158: sub auto_courserequest_validation {
1.1172.2.43 raeburn 8159: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8160: my ($homeserver,$response);
8161: if ($dom =~ /^$match_domain$/) {
8162: $homeserver = &domain($dom,'primary');
8163: }
1.1172.2.43 raeburn 8164: unless ($homeserver eq 'no_host') {
8165: my $customdata;
8166: if (ref($custominfo) eq 'HASH') {
8167: $customdata = &freeze_escape($custominfo);
8168: }
1.1020 raeburn 8169: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8170: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 8171: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8172: $customdata,$homeserver));
1.1020 raeburn 8173: }
8174: return $response;
8175: }
8176:
1.777 albertel 8177: sub auto_validate_class_sec {
1.918 raeburn 8178: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8179: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8180: my $ownerlist;
8181: if (ref($owners) eq 'ARRAY') {
8182: $ownerlist = join(',',@{$owners});
8183: } else {
8184: $ownerlist = $owners;
8185: }
1.773 raeburn 8186: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8187: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8188: return $response;
8189: }
8190:
1.1172.2.38 raeburn 8191: sub auto_crsreq_update {
8192: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 8193: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 8194: my ($homeserver,%crsreqresponse);
8195: if ($cdom =~ /^$match_domain$/) {
8196: $homeserver = &domain($cdom,'primary');
8197: }
8198: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8199: my $info;
8200: if (ref($inbound) eq 'HASH') {
8201: $info = &freeze_escape($inbound);
8202: }
8203: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8204: ':'.&escape($action).':'.&escape($ownername).':'.
8205: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 8206: &escape($title).':'.&escape($code).':'.
8207: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 8208: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8209: my @items = split(/&/,$response);
8210: foreach my $item (@items) {
8211: my ($key,$value) = split('=',$item);
8212: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8213: }
8214: }
8215: }
8216: return \%crsreqresponse;
8217: }
8218:
1.1172.2.68 raeburn 8219: sub check_instcode_cloning {
8220: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8221: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8222: return;
8223: }
8224: my $canclone;
8225: if (@{$code_order} > 0) {
8226: my $instcoderegexp ='^';
8227: my @clonecodes = split(/\&/,$cloner);
8228: foreach my $item (@{$code_order}) {
8229: if (grep(/^\Q$item\E=/,@clonecodes)) {
8230: foreach my $pair (@clonecodes) {
8231: my ($key,$val) = split(/\=/,$pair,2);
8232: $val = &unescape($val);
8233: if ($key eq $item) {
8234: $instcoderegexp .= '('.$val.')';
8235: last;
8236: }
8237: }
8238: } else {
8239: $instcoderegexp .= $codedefaults->{$item};
8240: }
8241: }
8242: $instcoderegexp .= '$';
8243: my (@from,@to);
8244: eval {
8245: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8246: (@to) = ($clonetocode =~ /$instcoderegexp/);
8247: };
8248: if ((@from > 0) && (@to > 0)) {
8249: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8250: if (!@diffs) {
8251: $canclone = 1;
8252: }
8253: }
8254: }
8255: return $canclone;
8256: }
8257:
8258: sub default_instcode_cloning {
8259: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8260: my (%codedefaults,@code_order,$canclone);
8261: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8262: %codedefaults = %{$codedefaultsref};
8263: @code_order = @{$codeorderref};
8264: } elsif ($clonedom) {
8265: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8266: }
8267: if (($domdefclone) && (@code_order)) {
8268: my @clonecodes = split(/\+/,$domdefclone);
8269: my $instcoderegexp ='^';
8270: foreach my $item (@code_order) {
8271: if (grep(/^\Q$item\E$/,@clonecodes)) {
8272: $instcoderegexp .= '('.$codedefaults{$item}.')';
8273: } else {
8274: $instcoderegexp .= $codedefaults{$item};
8275: }
8276: }
8277: $instcoderegexp .= '$';
8278: my (@from,@to);
8279: eval {
8280: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8281: (@to) = ($clonetocode =~ /$instcoderegexp/);
8282: };
8283: if ((@from > 0) && (@to > 0)) {
8284: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8285: if (!@diffs) {
8286: $canclone = 1;
8287: }
8288: }
8289: }
8290: return $canclone;
8291: }
8292:
1.679 raeburn 8293: # ------------------------------------------------------- Course Group routines
8294:
8295: sub get_coursegroups {
1.809 raeburn 8296: my ($cdom,$cnum,$group,$namespace) = @_;
8297: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8298: }
8299:
1.679 raeburn 8300: sub modify_coursegroup {
8301: my ($cdom,$cnum,$groupsettings) = @_;
8302: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8303: }
8304:
1.809 raeburn 8305: sub toggle_coursegroup_status {
8306: my ($cdom,$cnum,$group,$action) = @_;
8307: my ($from_namespace,$to_namespace);
8308: if ($action eq 'delete') {
8309: $from_namespace = 'coursegroups';
8310: $to_namespace = 'deleted_groups';
8311: } else {
8312: $from_namespace = 'deleted_groups';
8313: $to_namespace = 'coursegroups';
8314: }
8315: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8316: if (my $tmp = &error(%curr_group)) {
8317: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8318: return ('read error',$tmp);
8319: } else {
8320: my %savedsettings = %curr_group;
1.809 raeburn 8321: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8322: my $deloutcome;
8323: if ($result eq 'ok') {
1.809 raeburn 8324: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8325: } else {
8326: return ('write error',$result);
8327: }
8328: if ($deloutcome eq 'ok') {
8329: return 'ok';
8330: } else {
8331: return ('delete error',$deloutcome);
8332: }
8333: }
8334: }
8335:
1.679 raeburn 8336: sub modify_group_roles {
1.957 raeburn 8337: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8338: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8339: my $role = 'gr/'.&escape($userprivs);
8340: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8341: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8342: if ($result eq 'ok') {
8343: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8344: }
1.679 raeburn 8345: return $result;
8346: }
8347:
8348: sub modify_coursegroup_membership {
8349: my ($cdom,$cnum,$membership) = @_;
8350: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8351: return $result;
8352: }
8353:
1.682 raeburn 8354: sub get_active_groups {
8355: my ($udom,$uname,$cdom,$cnum) = @_;
8356: my $now = time;
8357: my %groups = ();
8358: foreach my $key (keys(%env)) {
1.811 albertel 8359: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8360: my ($start,$end) = split(/\./,$env{$key});
8361: if (($end!=0) && ($end<$now)) { next; }
8362: if (($start!=0) && ($start>$now)) { next; }
8363: if ($1 eq $cdom && $2 eq $cnum) {
8364: $groups{$3} = $env{$key} ;
8365: }
8366: }
8367: }
8368: return %groups;
8369: }
8370:
1.683 raeburn 8371: sub get_group_membership {
8372: my ($cdom,$cnum,$group) = @_;
8373: return(&dump('groupmembership',$cdom,$cnum,$group));
8374: }
8375:
8376: sub get_users_groups {
8377: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8378: my @usersgroups;
1.683 raeburn 8379: my $cachetime=1800;
8380:
8381: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8382: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8383: if (defined($cached)) {
1.734 albertel 8384: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8385: } else {
8386: $grouplist = '';
1.816 raeburn 8387: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8388: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8389: my $access_end = $env{'course.'.$courseid.
8390: '.default_enrollment_end_date'};
8391: my $now = time;
8392: foreach my $key (keys(%roleshash)) {
8393: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8394: my $group = $1;
8395: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8396: my $start = $2;
8397: my $end = $1;
8398: if ($start == -1) { next; } # deleted from group
8399: if (($start!=0) && ($start>$now)) { next; }
8400: if (($end!=0) && ($end<$now)) {
8401: if ($access_end && $access_end < $now) {
8402: if ($access_end - $end < 86400) {
8403: push(@usersgroups,$group);
1.733 raeburn 8404: }
8405: }
1.817 raeburn 8406: next;
1.733 raeburn 8407: }
1.817 raeburn 8408: push(@usersgroups,$group);
1.683 raeburn 8409: }
8410: }
8411: }
1.817 raeburn 8412: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8413: $grouplist = join(':',@usersgroups);
8414: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8415: }
1.733 raeburn 8416: return @usersgroups;
1.683 raeburn 8417: }
8418:
8419: sub devalidate_getgroups_cache {
8420: my ($udom,$uname,$cdom,$cnum)=@_;
8421: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8422:
1.683 raeburn 8423: my $hashid="$udom:$uname:$courseid";
8424: &devalidate_cache_new('getgroups',$hashid);
8425: }
8426:
1.12 www 8427: # ------------------------------------------------------------------ Plain Text
8428:
8429: sub plaintext {
1.988 raeburn 8430: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8431: if ($short =~ m{^cr/}) {
1.758 albertel 8432: return (split('/',$short))[-1];
8433: }
1.742 raeburn 8434: if (!defined($cid)) {
8435: $cid = $env{'request.course.id'};
8436: }
8437: my %rolenames = (
1.1008 raeburn 8438: Course => 'std',
8439: Community => 'alt1',
1.742 raeburn 8440: );
1.1037 raeburn 8441: if ($cid ne '') {
8442: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8443: unless ($forcedefault) {
8444: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8445: &Apache::lonlocal::mt_escape(\$roletext);
8446: return &Apache::lonlocal::mt($roletext);
8447: }
8448: }
8449: }
8450: if ((defined($type)) && (defined($rolenames{$type})) &&
8451: (defined($rolenames{$type})) &&
8452: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8453: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8454: } elsif ($cid ne '') {
8455: my $crstype = $env{'course.'.$cid.'.type'};
8456: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8457: (defined($prp{$short}{$rolenames{$crstype}}))) {
8458: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8459: }
1.742 raeburn 8460: }
1.1037 raeburn 8461: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8462: }
8463:
8464: # ----------------------------------------------------------------- Assign Role
8465:
8466: sub assignrole {
1.957 raeburn 8467: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8468: $context)=@_;
1.21 www 8469: my $mrole;
8470: if ($role =~ /^cr\//) {
1.393 www 8471: my $cwosec=$url;
1.811 albertel 8472: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8473: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8474: my $refused = 1;
8475: if ($context eq 'requestcourses') {
8476: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8477: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8478: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8479: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8480: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8481: if ($crsenv{'internal.courseowner'} eq
8482: $env{'user.name'}.':'.$env{'user.domain'}) {
8483: $refused = '';
8484: }
8485: }
8486: }
8487: }
8488: }
8489: if ($refused) {
8490: &logthis('Refused custom assignrole: '.
8491: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8492: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8493: return 'refused';
8494: }
1.104 www 8495: }
1.21 www 8496: $mrole='cr';
1.678 raeburn 8497: } elsif ($role =~ /^gr\//) {
8498: my $cwogrp=$url;
1.811 albertel 8499: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8500: unless (&allowed('mdg',$cwogrp)) {
8501: &logthis('Refused group assignrole: '.
8502: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8503: $env{'user.name'}.' at '.$env{'user.domain'});
8504: return 'refused';
8505: }
8506: $mrole='gr';
1.21 www 8507: } else {
1.82 www 8508: my $cwosec=$url;
1.811 albertel 8509: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8510: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8511: my $refused;
8512: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8513: if (!(&allowed('c'.$role,$url))) {
8514: $refused = 1;
8515: }
8516: } else {
8517: $refused = 1;
8518: }
1.947 raeburn 8519: if ($refused) {
1.1045 raeburn 8520: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8521: if (!$selfenroll && $context eq 'course') {
8522: my %crsenv;
8523: if ($role eq 'cc' || $role eq 'co') {
8524: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8525: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8526: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8527: if ($crsenv{'internal.courseowner'} eq
8528: $env{'user.name'}.':'.$env{'user.domain'}) {
8529: $refused = '';
8530: }
8531: }
8532: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8533: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8534: if ($crsenv{'internal.courseowner'} eq
8535: $env{'user.name'}.':'.$env{'user.domain'}) {
8536: $refused = '';
8537: }
8538: }
8539: }
8540: }
8541: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8542: $refused = '';
1.1017 raeburn 8543: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8544: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8545: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8546: my $wrongcc;
8547: if ($cnum =~ /^$match_community$/) {
8548: $wrongcc = 1 if ($role eq 'cc');
8549: } else {
8550: $wrongcc = 1 if ($role eq 'co');
8551: }
8552: unless ($wrongcc) {
8553: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8554: if ($crsenv{'internal.courseowner'} eq
8555: $env{'user.name'}.':'.$env{'user.domain'}) {
8556: $refused = '';
8557: }
1.1017 raeburn 8558: }
8559: }
1.1172.2.9 raeburn 8560: } elsif ($context eq 'requestauthor') {
8561: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8562: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8563: if ($env{'environment.requestauthor'} eq 'automatic') {
8564: $refused = '';
8565: } else {
8566: my %domdefaults = &get_domain_defaults($udom);
8567: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8568: my $checkbystatus;
8569: if ($env{'user.adv'}) {
8570: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8571: if ($disposition eq 'automatic') {
8572: $refused = '';
8573: } elsif ($disposition eq '') {
8574: $checkbystatus = 1;
8575: }
8576: } else {
8577: $checkbystatus = 1;
8578: }
8579: if ($checkbystatus) {
8580: if ($env{'environment.inststatus'}) {
8581: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8582: foreach my $type (@inststatuses) {
8583: if (($type ne '') &&
8584: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8585: $refused = '';
8586: }
8587: }
8588: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8589: $refused = '';
8590: }
8591: }
8592: }
8593: }
8594: }
1.1017 raeburn 8595: }
8596: if ($refused) {
1.947 raeburn 8597: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8598: ' '.$role.' '.$end.' '.$start.' by '.
8599: $env{'user.name'}.' at '.$env{'user.domain'});
8600: return 'refused';
8601: }
1.932 raeburn 8602: }
1.1131 raeburn 8603: } elsif ($role eq 'au') {
8604: if ($url ne '/'.$udom.'/') {
8605: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8606: ' to assign author role for '.$uname.':'.$udom.
8607: ' in domain: '.$url.' refused (wrong domain).');
8608: return 'refused';
8609: }
1.104 www 8610: }
1.21 www 8611: $mrole=$role;
8612: }
1.620 albertel 8613: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8614: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8615: if ($end) { $command.='_'.$end; }
1.21 www 8616: if ($start) {
8617: if ($end) {
1.81 www 8618: $command.='_'.$start;
1.21 www 8619: } else {
1.81 www 8620: $command.='_0_'.$start;
1.21 www 8621: }
8622: }
1.739 raeburn 8623: my $origstart = $start;
8624: my $origend = $end;
1.957 raeburn 8625: my $delflag;
1.357 www 8626: # actually delete
8627: if ($deleteflag) {
1.373 www 8628: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8629: # modify command to delete the role
1.620 albertel 8630: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8631: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8632: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8633: # set start and finish to negative values for userrolelog
8634: $start=-1;
8635: $end=-1;
1.957 raeburn 8636: $delflag = 1;
1.357 www 8637: }
8638: }
8639: # send command
1.349 www 8640: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8641: # log new user role if status is ok
1.349 www 8642: if ($answer eq 'ok') {
1.663 raeburn 8643: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 8644: if (($role eq 'cc') || ($role eq 'in') ||
8645: ($role eq 'ep') || ($role eq 'ad') ||
8646: ($role eq 'ta') || ($role eq 'st') ||
8647: ($role=~/^cr/) || ($role eq 'gr') ||
8648: ($role eq 'co')) {
1.1172.2.13 raeburn 8649: # for course roles, perform group memberships changes triggered by role change.
8650: unless ($role =~ /^gr/) {
8651: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8652: $origstart,$selfenroll,$context);
8653: }
1.1172.2.9 raeburn 8654: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8655: $selfenroll,$context);
8656: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8657: ($role eq 'au') || ($role eq 'dc')) {
8658: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8659: $context);
8660: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8661: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8662: $context);
8663: }
1.1053 raeburn 8664: if ($role eq 'cc') {
8665: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8666: }
1.349 www 8667: }
8668: return $answer;
1.169 harris41 8669: }
8670:
1.1053 raeburn 8671: sub autoupdate_coowners {
8672: my ($url,$end,$start,$uname,$udom) = @_;
8673: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8674: if (($cdom ne '') && ($cnum ne '')) {
8675: my $now = time;
8676: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8677: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8678: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8679: my $instcode = $coursehash{'internal.coursecode'};
8680: if ($instcode ne '') {
1.1056 raeburn 8681: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8682: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8683: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8684: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8685: if ($result eq 'valid') {
8686: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8687: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8688: push(@newcoowners,$coowner);
8689: }
8690: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8691: push(@newcoowners,$uname.':'.$udom);
8692: }
8693: @newcoowners = sort(@newcoowners);
8694: } else {
8695: push(@newcoowners,$uname.':'.$udom);
8696: }
8697: } else {
8698: if ($coursehash{'internal.co-owners'}) {
8699: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8700: unless ($coowner eq $uname.':'.$udom) {
8701: push(@newcoowners,$coowner);
8702: }
8703: }
8704: unless (@newcoowners > 0) {
8705: $delcoowners = 1;
8706: $coowners = '';
8707: }
8708: }
8709: }
8710: if (@newcoowners || $delcoowners) {
8711: &store_coowners($cdom,$cnum,$coursehash{'home'},
8712: $delcoowners,@newcoowners);
8713: }
8714: }
8715: }
8716: }
8717: }
8718: }
8719: }
8720:
8721: sub store_coowners {
8722: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8723: my $cid = $cdom.'_'.$cnum;
8724: my ($coowners,$delresult,$putresult);
8725: if (@newcoowners) {
8726: $coowners = join(',',@newcoowners);
8727: my %coownershash = (
8728: 'internal.co-owners' => $coowners,
8729: );
8730: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8731: if ($putresult eq 'ok') {
8732: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8733: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8734: }
8735: }
8736: }
8737: if ($delcoowners) {
8738: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8739: if ($delresult eq 'ok') {
8740: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8741: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8742: }
8743: }
8744: }
8745: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8746: my %crsinfo =
8747: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8748: if (ref($crsinfo{$cid}) eq 'HASH') {
8749: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8750: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8751: }
8752: }
8753: }
8754:
1.169 harris41 8755: # -------------------------------------------------- Modify user authentication
1.197 www 8756: # Overrides without validation
8757:
1.169 harris41 8758: sub modifyuserauth {
8759: my ($udom,$uname,$umode,$upass)=@_;
8760: my $uhome=&homeserver($uname,$udom);
1.197 www 8761: unless (&allowed('mau',$udom)) { return 'refused'; }
8762: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8763: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8764: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8765: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8766: &escape($upass),$uhome);
1.620 albertel 8767: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8768: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8769: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8770: &log($udom,,$uname,$uhome,
1.620 albertel 8771: 'Authentication changed by '.$env{'user.domain'}.', '.
8772: $env{'user.name'}.', '.$umode.
1.197 www 8773: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8774: unless ($reply eq 'ok') {
1.197 www 8775: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8776: return 'error: '.$reply;
8777: }
1.170 harris41 8778: return 'ok';
1.80 www 8779: }
8780:
1.81 www 8781: # --------------------------------------------------------------- Modify a user
1.80 www 8782:
1.81 www 8783: sub modifyuser {
1.206 matthew 8784: my ($udom, $uname, $uid,
8785: $umode, $upass, $first,
8786: $middle, $last, $gene,
1.1058 raeburn 8787: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8788: $udom= &LONCAPA::clean_domain($udom);
8789: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8790: my $showcandelete = 'none';
8791: if (ref($candelete) eq 'ARRAY') {
8792: if (@{$candelete} > 0) {
8793: $showcandelete = join(', ',@{$candelete});
8794: }
8795: }
1.81 www 8796: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8797: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8798: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8799: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8800: ' desiredhome not specified').
1.620 albertel 8801: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8802: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8803: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8804: my $newuser;
8805: if ($uhome eq 'no_host') {
8806: $newuser = 1;
8807: }
1.80 www 8808: # ----------------------------------------------------------------- Create User
1.406 albertel 8809: if (($uhome eq 'no_host') &&
8810: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8811: my $unhome='';
1.844 albertel 8812: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8813: $unhome = $desiredhome;
1.620 albertel 8814: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8815: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8816: } else { # load balancing routine for determining $unhome
1.81 www 8817: my $loadm=10000000;
1.841 albertel 8818: my %servers = &get_servers($udom,'library');
8819: foreach my $tryserver (keys(%servers)) {
8820: my $answer=reply('load',$tryserver);
8821: if (($answer=~/\d+/) && ($answer<$loadm)) {
8822: $loadm=$answer;
8823: $unhome=$tryserver;
8824: }
1.80 www 8825: }
8826: }
8827: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8828: return 'error: unable to find a home server for '.$uname.
8829: ' in domain '.$udom;
1.80 www 8830: }
8831: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8832: &escape($upass),$unhome);
8833: unless ($reply eq 'ok') {
8834: return 'error: '.$reply;
8835: }
1.230 stredwic 8836: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8837: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8838: return 'error: unable verify users home machine.';
1.80 www 8839: }
1.209 matthew 8840: } # End of creation of new user
1.80 www 8841: # ---------------------------------------------------------------------- Add ID
8842: if ($uid) {
8843: $uid=~tr/A-Z/a-z/;
8844: my %uidhash=&idrget($udom,$uname);
1.196 www 8845: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8846: && (!$forceid)) {
1.80 www 8847: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8848: return 'error: user id "'.$uid.'" does not match '.
8849: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8850: }
8851: } else {
8852: &idput($udom,($uname => $uid));
8853: }
8854: }
8855: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8856: my @tmp=&get('environment',
1.899 raeburn 8857: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8858: 'permanentemail','inststatus'],
1.134 albertel 8859: $udom,$uname);
1.1075 raeburn 8860: my (%names,%oldnames);
1.313 matthew 8861: if ($tmp[0] =~ m/^error:.*/) {
8862: %names=();
8863: } else {
8864: %names = @tmp;
1.1075 raeburn 8865: %oldnames = %names;
1.313 matthew 8866: }
1.388 www 8867: #
1.1058 raeburn 8868: # If name, email and/or uid are blank (e.g., because an uploaded file
8869: # of users did not contain them), do not overwrite existing values
8870: # unless field is in $candelete array ref.
8871: #
8872:
8873: my @fields = ('firstname','middlename','lastname','generation',
8874: 'permanentemail','id');
8875: my %newvalues;
8876: if (ref($candelete) eq 'ARRAY') {
8877: foreach my $field (@fields) {
8878: if (grep(/^\Q$field\E$/,@{$candelete})) {
8879: if ($field eq 'firstname') {
8880: $names{$field} = $first;
8881: } elsif ($field eq 'middlename') {
8882: $names{$field} = $middle;
8883: } elsif ($field eq 'lastname') {
8884: $names{$field} = $last;
8885: } elsif ($field eq 'generation') {
8886: $names{$field} = $gene;
8887: } elsif ($field eq 'permanentemail') {
8888: $names{$field} = $email;
8889: } elsif ($field eq 'id') {
8890: $names{$field} = $uid;
8891: }
8892: }
8893: }
8894: }
1.388 www 8895: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8896: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8897: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8898: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8899: if ($email) {
8900: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8901: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8902: }
1.899 raeburn 8903: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8904: if (defined($inststatus)) {
8905: $names{'inststatus'} = '';
8906: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8907: if (ref($usertypes) eq 'HASH') {
8908: my @okstatuses;
8909: foreach my $item (split(/:/,$inststatus)) {
8910: if (defined($usertypes->{$item})) {
8911: push(@okstatuses,$item);
8912: }
8913: }
8914: if (@okstatuses) {
8915: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8916: }
8917: }
8918: }
1.1075 raeburn 8919: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8920: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8921: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8922: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8923: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8924: } else {
8925: $logmsg .= ' during self creation';
8926: }
1.1075 raeburn 8927: my $changed;
8928: if ($newuser) {
8929: $changed = 1;
8930: } else {
8931: foreach my $field (@fields) {
8932: if ($names{$field} ne $oldnames{$field}) {
8933: $changed = 1;
8934: last;
8935: }
8936: }
8937: }
8938: unless ($changed) {
8939: $logmsg = 'No changes in user information needed for: '.$logmsg;
8940: &logthis($logmsg);
8941: return 'ok';
8942: }
8943: my $reply = &put('environment', \%names, $udom,$uname);
8944: if ($reply ne 'ok') {
8945: return 'error: '.$reply;
8946: }
1.1087 raeburn 8947: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8948: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8949: }
1.1075 raeburn 8950: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8951: &devalidate_cache_new('namescache',$uname.':'.$udom);
8952: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8953: &logthis($logmsg);
1.134 albertel 8954: return 'ok';
1.80 www 8955: }
8956:
1.81 www 8957: # -------------------------------------------------------------- Modify student
1.80 www 8958:
1.81 www 8959: sub modifystudent {
8960: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8961: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19 raeburn 8962: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8963: if (!$cid) {
1.620 albertel 8964: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8965: return 'not_in_class';
8966: }
1.80 www 8967: }
8968: # --------------------------------------------------------------- Make the user
1.81 www 8969: my $reply=&modifyuser
1.209 matthew 8970: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8971: $desiredhome,$email,$inststatus);
1.80 www 8972: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8973: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 8974: # student's environment
1.297 matthew 8975: $uid = undef if (!$forceid);
1.455 albertel 8976: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 8977: $gene,$usec,$end,$start,$type,$locktype,
8978: $cid,$selfenroll,$context,$credits);
1.297 matthew 8979: return $reply;
8980: }
8981:
8982: sub modify_student_enrollment {
1.1172.2.23 raeburn 8983: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8984: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8985: my ($cdom,$cnum,$chome);
8986: if (!$cid) {
1.620 albertel 8987: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8988: return 'not_in_class';
8989: }
1.620 albertel 8990: $cdom=$env{'course.'.$cid.'.domain'};
8991: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8992: } else {
8993: ($cdom,$cnum)=split(/_/,$cid);
8994: }
1.620 albertel 8995: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8996: if (!$chome) {
1.457 raeburn 8997: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8998: }
1.455 albertel 8999: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9000: # Make sure the user exists
1.81 www 9001: my $uhome=&homeserver($uname,$udom);
9002: if (($uhome eq '') || ($uhome eq 'no_host')) {
9003: return 'error: no such user';
9004: }
1.297 matthew 9005: # Get student data if we were not given enough information
9006: if (!defined($first) || $first eq '' ||
9007: !defined($last) || $last eq '' ||
9008: !defined($uid) || $uid eq '' ||
9009: !defined($middle) || $middle eq '' ||
9010: !defined($gene) || $gene eq '') {
1.294 matthew 9011: # They did not supply us with enough data to enroll the student, so
9012: # we need to pick up more information.
1.297 matthew 9013: my %tmp = &get('environment',
1.294 matthew 9014: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9015: ,$udom,$uname);
9016:
1.800 albertel 9017: #foreach my $key (keys(%tmp)) {
9018: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9019: #}
1.294 matthew 9020: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9021: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9022: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9023: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9024: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9025: }
1.556 albertel 9026: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9027: my $user = "$uname:$udom";
9028: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9029: my $reply=cput('classlist',
1.1148 raeburn 9030: {$user =>
1.1172.2.19 raeburn 9031: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 9032: $cdom,$cnum);
1.1148 raeburn 9033: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9034: &devalidate_getsection_cache($udom,$uname,$cid);
9035: } else {
1.81 www 9036: return 'error: '.$reply;
9037: }
1.297 matthew 9038: # Add student role to user
1.83 www 9039: my $uurl='/'.$cid;
1.81 www 9040: $uurl=~s/\_/\//g;
9041: if ($usec) {
9042: $uurl.='/'.$usec;
9043: }
1.1148 raeburn 9044: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9045: $selfenroll,$context);
9046: if ($result ne 'ok') {
9047: if ($old_entry{$user} ne '') {
9048: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9049: } else {
9050: $reply = &del('classlist',[$user],$cdom,$cnum);
9051: }
9052: }
9053: return $result;
1.21 www 9054: }
9055:
1.556 albertel 9056: sub format_name {
9057: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9058: my $name;
9059: if ($first ne 'lastname') {
9060: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9061: } else {
9062: if ($lastname=~/\S/) {
9063: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9064: $name=~s/\s+,/,/;
9065: } else {
9066: $name.= $firstname.' '.$middlename.' '.$generation;
9067: }
9068: }
9069: $name=~s/^\s+//;
9070: $name=~s/\s+$//;
9071: $name=~s/\s+/ /g;
9072: return $name;
9073: }
9074:
1.84 www 9075: # ------------------------------------------------- Write to course preferences
9076:
9077: sub writecoursepref {
9078: my ($courseid,%prefs)=@_;
9079: $courseid=~s/^\///;
9080: $courseid=~s/\_/\//g;
9081: my ($cdomain,$cnum)=split(/\//,$courseid);
9082: my $chome=homeserver($cnum,$cdomain);
9083: if (($chome eq '') || ($chome eq 'no_host')) {
9084: return 'error: no such course';
9085: }
9086: my $cstring='';
1.800 albertel 9087: foreach my $pref (keys(%prefs)) {
9088: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9089: }
1.84 www 9090: $cstring=~s/\&$//;
9091: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9092: }
9093:
9094: # ---------------------------------------------------------- Make/modify course
9095:
9096: sub createcourse {
1.741 raeburn 9097: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9098: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9099: $url=&declutter($url);
9100: my $cid='';
1.1028 raeburn 9101: if ($context eq 'requestcourses') {
9102: my $can_create = 0;
9103: my ($ownername,$ownerdom) = split(':',$course_owner);
9104: if ($udom eq $ownerdom) {
9105: if (&usertools_access($ownername,$ownerdom,$category,undef,
9106: $context)) {
9107: $can_create = 1;
9108: }
9109: } else {
9110: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9111: $category);
9112: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9113: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9114: if (@curr > 0) {
9115: my @options = qw(approval validate autolimit);
9116: my $optregex = join('|',@options);
9117: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9118: $can_create = 1;
9119: }
9120: }
9121: }
9122: }
9123: if ($can_create) {
9124: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9125: unless (&allowed('ccc',$udom)) {
9126: return 'refused';
9127: }
1.1017 raeburn 9128: }
9129: } else {
9130: return 'refused';
9131: }
1.1028 raeburn 9132: } elsif (!&allowed('ccc',$udom)) {
9133: return 'refused';
1.84 www 9134: }
1.1011 raeburn 9135: # --------------------------------------------------------------- Get Unique ID
9136: my $uname;
9137: if ($cnum =~ /^$match_courseid$/) {
9138: my $chome=&homeserver($cnum,$udom,'true');
9139: if (($chome eq '') || ($chome eq 'no_host')) {
9140: $uname = $cnum;
9141: } else {
1.1038 raeburn 9142: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9143: }
9144: } else {
1.1038 raeburn 9145: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9146: }
9147: return $uname if ($uname =~ /^error/);
9148: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9149: if (!defined($course_server)) {
9150: if (defined(&domain($udom,'primary'))) {
9151: $course_server = &domain($udom,'primary');
9152: } else {
9153: $course_server = $env{'user.home'};
9154: }
9155: }
9156: my %host_servers =
9157: &Apache::lonnet::get_servers($udom,'library');
9158: unless ($host_servers{$course_server}) {
9159: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9160: }
1.84 www 9161: # ------------------------------------------------------------- Make the course
9162: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9163: $course_server);
1.84 www 9164: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9165: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9166: if (($uhome eq '') || ($uhome eq 'no_host')) {
9167: return 'error: no such course';
9168: }
1.271 www 9169: # ----------------------------------------------------------------- Course made
1.516 raeburn 9170: # log existence
1.1029 raeburn 9171: my $now = time;
1.918 raeburn 9172: my $newcourse = {
9173: $udom.'_'.$uname => {
1.921 raeburn 9174: description => $description,
9175: inst_code => $inst_code,
9176: owner => $course_owner,
9177: type => $crstype,
1.1029 raeburn 9178: creator => $env{'user.name'}.':'.
9179: $env{'user.domain'},
9180: created => $now,
9181: context => $context,
1.918 raeburn 9182: },
9183: };
1.921 raeburn 9184: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9185: # set toplevel url
1.271 www 9186: my $topurl=$url;
9187: unless ($nonstandard) {
9188: # ------------------------------------------ For standard courses, make top url
9189: my $mapurl=&clutter($url);
1.278 www 9190: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9191: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9192: <map>
9193: <resource id="1" type="start"></resource>
9194: <resource id="2" src="$mapurl"></resource>
9195: <resource id="3" type="finish"></resource>
9196: <link index="1" from="1" to="2"></link>
9197: <link index="2" from="2" to="3"></link>
9198: </map>
9199: ENDINITMAP
9200: $topurl=&declutter(
1.638 albertel 9201: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9202: );
9203: }
9204: # ----------------------------------------------------------- Write preferences
1.84 www 9205: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9206: ('description' => $description,
9207: 'url' => $topurl,
9208: 'internal.creator' => $env{'user.name'}.':'.
9209: $env{'user.domain'},
9210: 'internal.created' => $now,
9211: 'internal.creationcontext' => $context)
9212: );
1.84 www 9213: return '/'.$udom.'/'.$uname;
9214: }
9215:
1.1011 raeburn 9216: # ------------------------------------------------------------------- Create ID
9217: sub generate_coursenum {
1.1038 raeburn 9218: my ($udom,$crstype) = @_;
1.1011 raeburn 9219: my $domdesc = &domain($udom);
9220: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9221: my $first;
9222: if ($crstype eq 'Community') {
9223: $first = '0';
9224: } else {
9225: $first = int(1+rand(9));
9226: }
9227: my $uname=$first.
1.1011 raeburn 9228: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9229: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9230: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9231: # ----------------------------------------------- Make sure that does not exist
9232: my $uhome=&homeserver($uname,$udom,'true');
9233: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9234: if ($crstype eq 'Community') {
9235: $first = '0';
9236: } else {
9237: $first = int(1+rand(9));
9238: }
9239: $uname=$first.
1.1011 raeburn 9240: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9241: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9242: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9243: $uhome=&homeserver($uname,$udom,'true');
9244: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9245: return 'error: unable to generate unique course-ID';
9246: }
9247: }
9248: return $uname;
9249: }
9250:
1.813 albertel 9251: sub is_course {
1.1167 droeschl 9252: my ($cdom, $cnum) = scalar(@_) == 1 ?
9253: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9254:
9255: return unless $cdom and $cnum;
9256:
9257: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9258: '.');
9259:
1.1172.2.23 raeburn 9260: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9261: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9262: }
9263:
1.1015 raeburn 9264: sub store_userdata {
9265: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9266: my $result;
1.1016 raeburn 9267: if ($datakey ne '') {
1.1013 raeburn 9268: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9269: if ($udom eq '' || $uname eq '') {
9270: $udom = $env{'user.domain'};
9271: $uname = $env{'user.name'};
9272: }
9273: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9274: if (($uhome eq '') || ($uhome eq 'no_host')) {
9275: $result = 'error: no_host';
9276: } else {
9277: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9278: $storehash->{'host'} = $perlvar{'lonHostID'};
9279:
9280: my $namevalue='';
9281: foreach my $key (keys(%{$storehash})) {
9282: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9283: }
9284: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 9285: unless ($namespace eq 'courserequests') {
9286: $datakey = &escape($datakey);
9287: }
1.1105 raeburn 9288: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9289: $namevalue,$uhome);
1.1013 raeburn 9290: }
9291: } else {
9292: $result = 'error: data to store was not a hash reference';
9293: }
9294: } else {
9295: $result= 'error: invalid requestkey';
9296: }
9297: return $result;
9298: }
9299:
1.21 www 9300: # ---------------------------------------------------------- Assign Custom Role
9301:
9302: sub assigncustomrole {
1.957 raeburn 9303: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9304: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9305: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9306: }
9307:
9308: # ----------------------------------------------------------------- Revoke Role
9309:
9310: sub revokerole {
1.957 raeburn 9311: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9312: my $now=time;
1.965 raeburn 9313: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9314: }
9315:
9316: # ---------------------------------------------------------- Revoke Custom Role
9317:
9318: sub revokecustomrole {
1.957 raeburn 9319: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9320: my $now=time;
1.357 www 9321: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9322: $deleteflag,$selfenroll,$context);
1.17 www 9323: }
9324:
1.533 banghart 9325: # ------------------------------------------------------------ Disk usage
1.535 albertel 9326: sub diskusage {
1.955 raeburn 9327: my ($udom,$uname,$directorypath,$getpropath)=@_;
9328: $directorypath =~ s/\/$//;
9329: my $listing=&reply('du2:'.&escape($directorypath).':'
9330: .&escape($getpropath).':'.&escape($uname).':'
9331: .&escape($udom),homeserver($uname,$udom));
9332: if ($listing eq 'unknown_cmd') {
9333: if ($getpropath) {
9334: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9335: }
9336: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9337: }
1.514 albertel 9338: return $listing;
1.512 banghart 9339: }
9340:
1.566 banghart 9341: sub is_locked {
1.1096 raeburn 9342: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9343: my @check;
9344: my $is_locked;
1.1093 raeburn 9345: push (@check,$file_name);
1.613 albertel 9346: my %locked = &get('file_permissions',\@check,
1.620 albertel 9347: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9348: my ($tmp)=keys(%locked);
9349: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9350:
1.566 banghart 9351: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9352: $is_locked = 'false';
9353: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9354: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9355: $is_locked = 'true';
1.1096 raeburn 9356: if (ref($which) eq 'ARRAY') {
9357: push(@{$which},$entry);
9358: } else {
9359: last;
9360: }
1.745 raeburn 9361: }
9362: }
1.566 banghart 9363: } else {
9364: $is_locked = 'false';
9365: }
1.1093 raeburn 9366: return $is_locked;
1.566 banghart 9367: }
9368:
1.759 albertel 9369: sub declutter_portfile {
9370: my ($file) = @_;
1.833 albertel 9371: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9372: return $file;
9373: }
9374:
1.559 banghart 9375: # ------------------------------------------------------------- Mark as Read Only
9376:
9377: sub mark_as_readonly {
9378: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9379: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9380: my ($tmp)=keys(%current_permissions);
9381: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9382: foreach my $file (@{$files}) {
1.759 albertel 9383: $file = &declutter_portfile($file);
1.561 banghart 9384: push(@{$current_permissions{$file}},$what);
1.559 banghart 9385: }
1.613 albertel 9386: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9387: return;
9388: }
9389:
1.572 banghart 9390: # ------------------------------------------------------------Save Selected Files
9391:
9392: sub save_selected_files {
9393: my ($user, $path, @files) = @_;
9394: my $filename = $user."savedfiles";
1.573 banghart 9395: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9396: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9397: foreach my $file (@files) {
1.620 albertel 9398: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9399: }
9400: foreach my $file (@other_files) {
1.574 banghart 9401: print (OUT $file."\n");
1.572 banghart 9402: }
1.574 banghart 9403: close (OUT);
1.572 banghart 9404: return 'ok';
9405: }
9406:
1.574 banghart 9407: sub clear_selected_files {
9408: my ($user) = @_;
9409: my $filename = $user."savedfiles";
1.1117 foxr 9410: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9411: print (OUT undef);
9412: close (OUT);
9413: return ("ok");
9414: }
9415:
1.572 banghart 9416: sub files_in_path {
9417: my ($user, $path) = @_;
9418: my $filename = $user."savedfiles";
9419: my %return_files;
1.1117 foxr 9420: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9421: while (my $line_in = <IN>) {
1.574 banghart 9422: chomp ($line_in);
9423: my @paths_and_file = split (m!/!, $line_in);
9424: my $file_part = pop (@paths_and_file);
9425: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9426: $path_part.='/';
9427: my $path_and_file = $path_part.$file_part;
9428: if ($path_part eq $path) {
9429: $return_files{$file_part}= 'selected';
9430: }
9431: }
1.574 banghart 9432: close (IN);
9433: return (\%return_files);
1.572 banghart 9434: }
9435:
9436: # called in portfolio select mode, to show files selected NOT in current directory
9437: sub files_not_in_path {
9438: my ($user, $path) = @_;
9439: my $filename = $user."savedfiles";
9440: my @return_files;
9441: my $path_part;
1.1117 foxr 9442: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9443: while (my $line = <IN>) {
1.572 banghart 9444: #ok, I know it's clunky, but I want it to work
1.800 albertel 9445: my @paths_and_file = split(m|/|, $line);
9446: my $file_part = pop(@paths_and_file);
9447: chomp($file_part);
9448: my $path_part = join('/', @paths_and_file);
1.572 banghart 9449: $path_part .= '/';
9450: my $path_and_file = $path_part.$file_part;
9451: if ($path_part ne $path) {
1.800 albertel 9452: push(@return_files, ($path_and_file));
1.572 banghart 9453: }
9454: }
1.800 albertel 9455: close(OUT);
1.574 banghart 9456: return (@return_files);
1.572 banghart 9457: }
9458:
1.745 raeburn 9459: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9460:
1.745 raeburn 9461: sub get_portfile_permissions {
9462: my ($domain,$user) = @_;
1.613 albertel 9463: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9464: my ($tmp)=keys(%current_permissions);
9465: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9466: return \%current_permissions;
9467: }
9468:
9469: #---------------------------------------------Get portfolio file access controls
9470:
1.749 raeburn 9471: sub get_access_controls {
1.745 raeburn 9472: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9473: my %access;
9474: my $real_file = $file;
9475: $file =~ s/\.meta$//;
1.745 raeburn 9476: if (defined($file)) {
1.749 raeburn 9477: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9478: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9479: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9480: }
9481: }
1.745 raeburn 9482: } else {
1.749 raeburn 9483: foreach my $key (keys(%{$current_permissions})) {
9484: if ($key =~ /\0accesscontrol$/) {
9485: if (defined($group)) {
9486: if ($key !~ m-^\Q$group\E/-) {
9487: next;
9488: }
9489: }
9490: my ($fullpath) = split(/\0/,$key);
9491: if (ref($$current_permissions{$key}) eq 'HASH') {
9492: foreach my $control (keys(%{$$current_permissions{$key}})) {
9493: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9494: }
9495: }
9496: }
9497: }
9498: }
9499: return %access;
9500: }
9501:
9502: sub modify_access_controls {
9503: my ($file_name,$changes,$domain,$user)=@_;
9504: my ($outcome,$deloutcome);
9505: my %store_permissions;
9506: my %new_values;
9507: my %new_control;
9508: my %translation;
9509: my @deletions = ();
9510: my $now = time;
9511: if (exists($$changes{'activate'})) {
9512: if (ref($$changes{'activate'}) eq 'HASH') {
9513: my @newitems = sort(keys(%{$$changes{'activate'}}));
9514: my $numnew = scalar(@newitems);
9515: for (my $i=0; $i<$numnew; $i++) {
9516: my $newkey = $newitems[$i];
9517: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9518: if ($newkey =~ /^\d+:/) {
9519: $newkey =~ s/^(\d+)/$newid/;
9520: $translation{$1} = $newid;
9521: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9522: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9523: $translation{$1} = $newid;
9524: }
1.749 raeburn 9525: $new_values{$file_name."\0".$newkey} =
9526: $$changes{'activate'}{$newitems[$i]};
9527: $new_control{$newkey} = $now;
9528: }
9529: }
9530: }
9531: my %todelete;
9532: my %changed_items;
9533: foreach my $action ('delete','update') {
9534: if (exists($$changes{$action})) {
9535: if (ref($$changes{$action}) eq 'HASH') {
9536: foreach my $key (keys(%{$$changes{$action}})) {
9537: my ($itemnum) = ($key =~ /^([^:]+):/);
9538: if ($action eq 'delete') {
9539: $todelete{$itemnum} = 1;
9540: } else {
9541: $changed_items{$itemnum} = $key;
9542: }
9543: }
1.745 raeburn 9544: }
9545: }
1.749 raeburn 9546: }
9547: # get lock on access controls for file.
9548: my $lockhash = {
9549: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9550: ':'.$env{'user.domain'},
9551: };
9552: my $tries = 0;
9553: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9554:
9555: while (($gotlock ne 'ok') && $tries <3) {
9556: $tries ++;
9557: sleep 1;
9558: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9559: }
9560: if ($gotlock eq 'ok') {
9561: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9562: my ($tmp)=keys(%curr_permissions);
9563: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9564: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9565: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9566: if (ref($curr_controls) eq 'HASH') {
9567: foreach my $control_item (keys(%{$curr_controls})) {
9568: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9569: if (defined($todelete{$itemnum})) {
9570: push(@deletions,$file_name."\0".$control_item);
9571: } else {
9572: if (defined($changed_items{$itemnum})) {
9573: $new_control{$changed_items{$itemnum}} = $now;
9574: push(@deletions,$file_name."\0".$control_item);
9575: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9576: } else {
9577: $new_control{$control_item} = $$curr_controls{$control_item};
9578: }
9579: }
1.745 raeburn 9580: }
9581: }
9582: }
1.970 raeburn 9583: my ($group);
9584: if (&is_course($domain,$user)) {
9585: ($group,my $file) = split(/\//,$file_name,2);
9586: }
1.749 raeburn 9587: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9588: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9589: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9590: # remove lock
9591: my @del_lock = ($file_name."\0".'locked_access_records');
9592: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9593: my $sqlresult =
1.970 raeburn 9594: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9595: $group);
1.749 raeburn 9596: } else {
9597: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9598: }
1.749 raeburn 9599: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9600: }
9601:
1.827 raeburn 9602: sub make_public_indefinitely {
9603: my ($requrl) = @_;
9604: my $now = time;
9605: my $action = 'activate';
9606: my $aclnum = 0;
9607: if (&is_portfolio_url($requrl)) {
9608: my (undef,$udom,$unum,$file_name,$group) =
9609: &parse_portfolio_url($requrl);
9610: my $current_perms = &get_portfile_permissions($udom,$unum);
9611: my %access_controls = &get_access_controls($current_perms,
9612: $group,$file_name);
9613: foreach my $key (keys(%{$access_controls{$file_name}})) {
9614: my ($num,$scope,$end,$start) =
9615: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9616: if ($scope eq 'public') {
9617: if ($start <= $now && $end == 0) {
9618: $action = 'none';
9619: } else {
9620: $action = 'update';
9621: $aclnum = $num;
9622: }
9623: last;
9624: }
9625: }
9626: if ($action eq 'none') {
9627: return 'ok';
9628: } else {
9629: my %changes;
9630: my $newend = 0;
9631: my $newstart = $now;
9632: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9633: $changes{$action}{$newkey} = {
9634: type => 'public',
9635: time => {
9636: start => $newstart,
9637: end => $newend,
9638: },
9639: };
9640: my ($outcome,$deloutcome,$new_values,$translation) =
9641: &modify_access_controls($file_name,\%changes,$udom,$unum);
9642: return $outcome;
9643: }
9644: } else {
9645: return 'invalid';
9646: }
9647: }
9648:
1.745 raeburn 9649: #------------------------------------------------------Get Marked as Read Only
9650:
9651: sub get_marked_as_readonly {
9652: my ($domain,$user,$what,$group) = @_;
9653: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9654: my @readonly_files;
1.629 banghart 9655: my $cmp1=$what;
9656: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9657: while (my ($file_name,$value) = each(%{$current_permissions})) {
9658: if (defined($group)) {
9659: if ($file_name !~ m-^\Q$group\E/-) {
9660: next;
9661: }
9662: }
1.561 banghart 9663: if (ref($value) eq "ARRAY"){
9664: foreach my $stored_what (@{$value}) {
1.629 banghart 9665: my $cmp2=$stored_what;
1.759 albertel 9666: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9667: $cmp2=join('',@{$stored_what});
1.745 raeburn 9668: }
1.629 banghart 9669: if ($cmp1 eq $cmp2) {
1.561 banghart 9670: push(@readonly_files, $file_name);
1.745 raeburn 9671: last;
1.563 banghart 9672: } elsif (!defined($what)) {
9673: push(@readonly_files, $file_name);
1.745 raeburn 9674: last;
1.561 banghart 9675: }
9676: }
1.745 raeburn 9677: }
1.561 banghart 9678: }
9679: return @readonly_files;
9680: }
1.577 banghart 9681: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9682:
1.577 banghart 9683: sub get_marked_as_readonly_hash {
1.745 raeburn 9684: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9685: my %readonly_files;
1.745 raeburn 9686: while (my ($file_name,$value) = each(%{$current_permissions})) {
9687: if (defined($group)) {
9688: if ($file_name !~ m-^\Q$group\E/-) {
9689: next;
9690: }
9691: }
1.577 banghart 9692: if (ref($value) eq "ARRAY"){
9693: foreach my $stored_what (@{$value}) {
1.745 raeburn 9694: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9695: foreach my $lock_descriptor(@{$stored_what}) {
9696: if ($lock_descriptor eq 'graded') {
9697: $readonly_files{$file_name} = 'graded';
9698: } elsif ($lock_descriptor eq 'handback') {
9699: $readonly_files{$file_name} = 'handback';
9700: } else {
9701: if (!exists($readonly_files{$file_name})) {
9702: $readonly_files{$file_name} = 'locked';
9703: }
9704: }
1.745 raeburn 9705: }
1.750 banghart 9706: }
1.577 banghart 9707: }
9708: }
9709: }
9710: return %readonly_files;
9711: }
1.559 banghart 9712: # ------------------------------------------------------------ Unmark as Read Only
9713:
9714: sub unmark_as_readonly {
1.629 banghart 9715: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9716: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9717: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9718: $file_name = &declutter_portfile($file_name);
1.634 albertel 9719: my $symb_crs = $what;
9720: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9721: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9722: my ($tmp)=keys(%current_permissions);
9723: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9724: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9725: foreach my $file (@readonly_files) {
1.759 albertel 9726: my $clean_file = &declutter_portfile($file);
9727: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9728: my $current_locks = $current_permissions{$file};
1.563 banghart 9729: my @new_locks;
9730: my @del_keys;
9731: if (ref($current_locks) eq "ARRAY"){
9732: foreach my $locker (@{$current_locks}) {
1.632 albertel 9733: my $compare=$locker;
1.749 raeburn 9734: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9735: $compare=join('',@{$locker});
1.746 raeburn 9736: if ($compare ne $symb_crs) {
9737: push(@new_locks, $locker);
9738: }
1.563 banghart 9739: }
9740: }
1.650 albertel 9741: if (scalar(@new_locks) > 0) {
1.563 banghart 9742: $current_permissions{$file} = \@new_locks;
9743: } else {
9744: push(@del_keys, $file);
1.613 albertel 9745: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9746: delete($current_permissions{$file});
1.563 banghart 9747: }
9748: }
1.561 banghart 9749: }
1.613 albertel 9750: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9751: return;
9752: }
1.512 banghart 9753:
1.17 www 9754: # ------------------------------------------------------------ Directory lister
9755:
9756: sub dirlist {
1.955 raeburn 9757: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9758: $uri=~s/^\///;
9759: $uri=~s/\/$//;
1.253 stredwic 9760: my ($udom, $uname);
1.955 raeburn 9761: if ($getuserdir) {
1.253 stredwic 9762: $udom = $userdomain;
9763: $uname = $username;
1.955 raeburn 9764: } else {
9765: (undef,$udom,$uname)=split(/\//,$uri);
9766: if(defined($userdomain)) {
9767: $udom = $userdomain;
9768: }
9769: if(defined($username)) {
9770: $uname = $username;
9771: }
1.253 stredwic 9772: }
1.955 raeburn 9773: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9774:
1.955 raeburn 9775: $dirRoot = $perlvar{'lonDocRoot'};
9776: if (defined($getpropath)) {
9777: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9778: $dirRoot =~ s/\/$//;
1.955 raeburn 9779: } elsif (defined($getuserdir)) {
9780: my $subdir=$uname.'__';
9781: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9782: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9783: ."/$udom/$subdir/$uname";
9784: } elsif (defined($alternateRoot)) {
9785: $dirRoot = $alternateRoot;
1.751 banghart 9786: }
1.253 stredwic 9787:
9788: if($udom) {
9789: if($uname) {
1.1135 raeburn 9790: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9791: if ($uhome eq 'no_host') {
9792: return ([],'no_host');
9793: }
1.955 raeburn 9794: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9795: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9796: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9797: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9798: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9799: } else {
9800: @listing_results = map { &unescape($_); } split(/:/,$listing);
9801: }
1.605 matthew 9802: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9803: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9804: @listing_results = split(/:/,$listing);
9805: } else {
9806: @listing_results = map { &unescape($_); } split(/:/,$listing);
9807: }
1.1135 raeburn 9808: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9809: ($listing eq 'rejected') || ($listing eq 'refused') ||
9810: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9811: return ([],$listing);
9812: } else {
9813: return (\@listing_results);
1.1135 raeburn 9814: }
1.955 raeburn 9815: } elsif(!$alternateRoot) {
1.1136 raeburn 9816: my (%allusers,%listerror);
1.841 albertel 9817: my %servers = &get_servers($udom,'library');
1.955 raeburn 9818: foreach my $tryserver (keys(%servers)) {
9819: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9820: &escape($udom),$tryserver);
9821: if ($listing eq 'unknown_cmd') {
9822: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9823: $udom, $tryserver);
9824: } else {
9825: @listing_results = map { &unescape($_); } split(/:/,$listing);
9826: }
1.841 albertel 9827: if ($listing eq 'unknown_cmd') {
9828: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9829: $udom, $tryserver);
9830: @listing_results = split(/:/,$listing);
9831: } else {
9832: @listing_results =
9833: map { &unescape($_); } split(/:/,$listing);
9834: }
1.1136 raeburn 9835: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9836: ($listing eq 'rejected') || ($listing eq 'refused') ||
9837: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9838: $listerror{$tryserver} = $listing;
9839: } else {
1.841 albertel 9840: foreach my $line (@listing_results) {
9841: my ($entry) = split(/&/,$line,2);
9842: $allusers{$entry} = 1;
9843: }
9844: }
1.253 stredwic 9845: }
1.1136 raeburn 9846: my @alluserslist=();
1.800 albertel 9847: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9848: push(@alluserslist,$user.'&user');
1.253 stredwic 9849: }
1.1136 raeburn 9850: return (\@alluserslist);
1.253 stredwic 9851: } else {
1.1136 raeburn 9852: return ([],'missing username');
1.253 stredwic 9853: }
1.955 raeburn 9854: } elsif(!defined($getpropath)) {
1.1136 raeburn 9855: my $path = $perlvar{'lonDocRoot'}.'/res/';
9856: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9857: return (\@all_domains);
1.955 raeburn 9858: } else {
1.1136 raeburn 9859: return ([],'missing domain');
1.275 stredwic 9860: }
9861: }
9862:
9863: # --------------------------------------------- GetFileTimestamp
9864: # This function utilizes dirlist and returns the date stamp for
9865: # when it was last modified. It will also return an error of -1
9866: # if an error occurs
9867:
9868: sub GetFileTimestamp {
1.955 raeburn 9869: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9870: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9871: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9872: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9873: undef,$getuserdir);
9874: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9875: return -1;
9876: }
9877: if (ref($fileref) eq 'ARRAY') {
9878: my @stats = split('&',$fileref->[0]);
1.375 matthew 9879: # @stats contains first the filename, then the stat output
9880: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9881: } else {
9882: return -1;
1.253 stredwic 9883: }
1.26 www 9884: }
9885:
1.712 albertel 9886: sub stat_file {
9887: my ($uri) = @_;
1.787 albertel 9888: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9889:
1.955 raeburn 9890: my ($udom,$uname,$file);
1.712 albertel 9891: if ($uri =~ m-^/(uploaded|editupload)/-) {
9892: ($udom,$uname,$file) =
1.811 albertel 9893: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9894: $file = 'userfiles/'.$file;
9895: }
9896: if ($uri =~ m-^/res/-) {
9897: ($udom,$uname) =
1.807 albertel 9898: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9899: $file = $uri;
9900: }
9901:
9902: if (!$udom || !$uname || !$file) {
9903: # unable to handle the uri
9904: return ();
9905: }
1.956 raeburn 9906: my $getpropath;
9907: if ($file =~ /^userfiles\//) {
9908: $getpropath = 1;
9909: }
1.1136 raeburn 9910: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9911: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9912: return ();
9913: } else {
9914: if (ref($listref) eq 'ARRAY') {
9915: my @stats = split('&',$listref->[0]);
9916: shift(@stats); #filename is first
9917: return @stats;
9918: }
1.712 albertel 9919: }
9920: return ();
9921: }
9922:
1.26 www 9923: # -------------------------------------------------------- Value of a Condition
9924:
1.713 albertel 9925: # gets the value of a specific preevaluated condition
9926: # stored in the string $env{user.state.<cid>}
9927: # or looks up a condition reference in the bighash and if if hasn't
9928: # already been evaluated recurses into docondval to get the value of
9929: # the condition, then memoizing it to
9930: # $env{user.state.<cid>.<condition>}
1.40 www 9931: sub directcondval {
9932: my $number=shift;
1.620 albertel 9933: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9934: &Apache::lonuserstate::evalstate();
9935: }
1.713 albertel 9936: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9937: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9938: } elsif ($number =~ /^_/) {
9939: my $sub_condition;
9940: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9941: &GDBM_READER(),0640)) {
9942: $sub_condition=$bighash{'conditions'.$number};
9943: untie(%bighash);
9944: }
9945: my $value = &docondval($sub_condition);
1.949 raeburn 9946: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9947: return $value;
9948: }
1.620 albertel 9949: if ($env{'user.state.'.$env{'request.course.id'}}) {
9950: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9951: } else {
9952: return 2;
9953: }
9954: }
9955:
1.713 albertel 9956: # get the collection of conditions for this resource
1.26 www 9957: sub condval {
9958: my $condidx=shift;
1.54 www 9959: my $allpathcond='';
1.713 albertel 9960: foreach my $cond (split(/\|/,$condidx)) {
9961: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9962: $allpathcond.=
9963: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9964: }
1.191 harris41 9965: }
1.54 www 9966: $allpathcond=~s/\|$//;
1.713 albertel 9967: return &docondval($allpathcond);
9968: }
9969:
9970: #evaluates an expression of conditions
9971: sub docondval {
9972: my ($allpathcond) = @_;
9973: my $result=0;
9974: if ($env{'request.course.id'}
9975: && defined($allpathcond)) {
9976: my $operand='|';
9977: my @stack;
9978: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9979: if ($chunk eq '(') {
9980: push @stack,($operand,$result);
9981: } elsif ($chunk eq ')') {
9982: my $before=pop @stack;
9983: if (pop @stack eq '&') {
9984: $result=$result>$before?$before:$result;
9985: } else {
9986: $result=$result>$before?$result:$before;
9987: }
9988: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9989: $operand=$chunk;
9990: } else {
9991: my $new=directcondval($chunk);
9992: if ($operand eq '&') {
9993: $result=$result>$new?$new:$result;
9994: } else {
9995: $result=$result>$new?$result:$new;
9996: }
9997: }
9998: }
1.26 www 9999: }
10000: return $result;
1.421 albertel 10001: }
10002:
10003: # ---------------------------------------------------- Devalidate courseresdata
10004:
10005: sub devalidatecourseresdata {
10006: my ($coursenum,$coursedomain)=@_;
10007: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10008: &devalidate_cache_new('courseres',$hashid);
1.28 www 10009: }
10010:
1.763 www 10011:
1.200 www 10012: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10013: #
10014: # Parameters:
10015: # $coursenum - Number of the course.
10016: # $coursedomain - Domain at which the course was created.
10017: # Returns:
10018: # A hash of the course parameters along (I think) with timestamps
10019: # and version info.
1.877 foxr 10020:
1.624 albertel 10021: sub get_courseresdata {
10022: my ($coursenum,$coursedomain)=@_;
1.200 www 10023: my $coursehom=&homeserver($coursenum,$coursedomain);
10024: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10025: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10026: my %dumpreply;
1.417 albertel 10027: unless (defined($cached)) {
1.624 albertel 10028: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10029: $result=\%dumpreply;
1.251 albertel 10030: my ($tmp) = keys(%dumpreply);
10031: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10032: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10033: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10034: return $tmp;
1.416 albertel 10035: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10036: $result=undef;
1.599 albertel 10037: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10038: }
10039: }
1.624 albertel 10040: return $result;
10041: }
10042:
1.633 albertel 10043: sub devalidateuserresdata {
10044: my ($uname,$udom)=@_;
10045: my $hashid="$udom:$uname";
10046: &devalidate_cache_new('userres',$hashid);
10047: }
10048:
1.624 albertel 10049: sub get_userresdata {
10050: my ($uname,$udom)=@_;
10051: #most student don\'t have any data set, check if there is some data
10052: if (&EXT_cache_status($udom,$uname)) { return undef; }
10053:
10054: my $hashid="$udom:$uname";
10055: my ($result,$cached)=&is_cached_new('userres',$hashid);
10056: if (!defined($cached)) {
10057: my %resourcedata=&dump('resourcedata',$udom,$uname);
10058: $result=\%resourcedata;
10059: &do_cache_new('userres',$hashid,$result,600);
10060: }
10061: my ($tmp)=keys(%$result);
10062: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10063: return $result;
10064: }
10065: #error 2 occurs when the .db doesn't exist
10066: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 10067: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10068: &logthis("<font color=\"blue\">WARNING:".
10069: " Trying to get resource data for ".
10070: $uname." at ".$udom.": ".
10071: $tmp."</font>");
10072: }
1.624 albertel 10073: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10074: #&EXT_cache_set($udom,$uname);
10075: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10076: undef($tmp); # not really an error so don't send it back
1.624 albertel 10077: }
10078: return $tmp;
10079: }
1.879 foxr 10080: #----------------------------------------------- resdata - return resource data
10081: # Purpose:
10082: # Return resource data for either users or for a course.
10083: # Parameters:
10084: # $name - Course/user name.
10085: # $domain - Name of the domain the user/course is registered on.
10086: # $type - Type of thing $name is (must be 'course' or 'user'
10087: # @which - Array of names of resources desired.
10088: # Returns:
10089: # The value of the first reasource in @which that is found in the
10090: # resource hash.
10091: # Exceptional Conditions:
10092: # If the $type passed in is not valid (not the string 'course' or
10093: # 'user', an undefined reference is returned.
10094: # If none of the resources are found, an undef is returned
1.624 albertel 10095: sub resdata {
10096: my ($name,$domain,$type,@which)=@_;
10097: my $result;
10098: if ($type eq 'course') {
10099: $result=&get_courseresdata($name,$domain);
10100: } elsif ($type eq 'user') {
10101: $result=&get_userresdata($name,$domain);
10102: }
10103: if (!ref($result)) { return $result; }
1.251 albertel 10104: foreach my $item (@which) {
1.927 albertel 10105: if (defined($result->{$item->[0]})) {
10106: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10107: }
1.250 albertel 10108: }
1.291 albertel 10109: return undef;
1.200 www 10110: }
10111:
1.1172.2.31 raeburn 10112: sub get_numsuppfiles {
10113: my ($cnum,$cdom,$ignorecache)=@_;
10114: my $hashid=$cnum.':'.$cdom;
10115: my ($suppcount,$cached);
10116: unless ($ignorecache) {
10117: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10118: }
10119: unless (defined($cached)) {
10120: my $chome=&homeserver($cnum,$cdom);
10121: unless ($chome eq 'no_host') {
10122: ($suppcount,my $errors) = (0,0);
10123: my $suppmap = 'supplemental.sequence';
10124: ($suppcount,$errors) =
10125: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10126: }
10127: &do_cache_new('suppcount',$hashid,$suppcount,600);
10128: }
10129: return $suppcount;
10130: }
10131:
1.379 matthew 10132: #
10133: # EXT resource caching routines
10134: #
10135:
10136: sub clear_EXT_cache_status {
1.383 albertel 10137: &delenv('cache.EXT.');
1.379 matthew 10138: }
10139:
10140: sub EXT_cache_status {
10141: my ($target_domain,$target_user) = @_;
1.383 albertel 10142: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10143: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10144: # We know already the user has no data
10145: return 1;
10146: } else {
10147: return 0;
10148: }
10149: }
10150:
10151: sub EXT_cache_set {
10152: my ($target_domain,$target_user) = @_;
1.383 albertel 10153: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10154: #&appenv({$cachename => time});
1.379 matthew 10155: }
10156:
1.28 www 10157: # --------------------------------------------------------- Value of a Variable
1.58 www 10158: sub EXT {
1.715 albertel 10159:
1.1172.2.28 raeburn 10160: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10161: unless ($varname) { return ''; }
1.218 albertel 10162: #get real user name/domain, courseid and symb
10163: my $courseid;
1.359 albertel 10164: my $publicuser;
1.427 www 10165: if ($symbparm) {
10166: $symbparm=&get_symb_from_alias($symbparm);
10167: }
1.218 albertel 10168: if (!($uname && $udom)) {
1.790 albertel 10169: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10170: if (!$symbparm) { $symbparm=$cursymb; }
10171: } else {
1.620 albertel 10172: $courseid=$env{'request.course.id'};
1.218 albertel 10173: }
1.48 www 10174: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10175: my $rest;
1.320 albertel 10176: if (defined($therest[0])) {
1.48 www 10177: $rest=join('.',@therest);
10178: } else {
10179: $rest='';
10180: }
1.320 albertel 10181:
1.57 www 10182: my $qualifierrest=$qualifier;
10183: if ($rest) { $qualifierrest.='.'.$rest; }
10184: my $spacequalifierrest=$space;
10185: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10186: if ($realm eq 'user') {
1.48 www 10187: # --------------------------------------------------------------- user.resource
10188: if ($space eq 'resource') {
1.651 albertel 10189: if ( (defined($Apache::lonhomework::parsing_a_problem)
10190: || defined($Apache::lonhomework::parsing_a_task))
10191: &&
1.744 albertel 10192: ($symbparm eq &symbread()) ) {
10193: # if we are in the middle of processing the resource the
10194: # get the value we are planning on committing
10195: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10196: return $Apache::lonhomework::results{$qualifierrest};
10197: } else {
10198: return $Apache::lonhomework::history{$qualifierrest};
10199: }
1.335 albertel 10200: } else {
1.359 albertel 10201: my %restored;
1.620 albertel 10202: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10203: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10204: } else {
10205: %restored=&restore($symbparm,$courseid,$udom,$uname);
10206: }
1.335 albertel 10207: return $restored{$qualifierrest};
10208: }
1.48 www 10209: # ----------------------------------------------------------------- user.access
10210: } elsif ($space eq 'access') {
1.218 albertel 10211: # FIXME - not supporting calls for a specific user
1.48 www 10212: return &allowed($qualifier,$rest);
10213: # ------------------------------------------ user.preferences, user.environment
10214: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10215: if (($uname eq $env{'user.name'}) &&
10216: ($udom eq $env{'user.domain'})) {
10217: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10218: } else {
1.359 albertel 10219: my %returnhash;
10220: if (!$publicuser) {
10221: %returnhash=&userenvironment($udom,$uname,
10222: $qualifierrest);
10223: }
1.218 albertel 10224: return $returnhash{$qualifierrest};
10225: }
1.48 www 10226: # ----------------------------------------------------------------- user.course
10227: } elsif ($space eq 'course') {
1.218 albertel 10228: # FIXME - not supporting calls for a specific user
1.620 albertel 10229: return $env{join('.',('request.course',$qualifier))};
1.48 www 10230: # ------------------------------------------------------------------- user.role
10231: } elsif ($space eq 'role') {
1.218 albertel 10232: # FIXME - not supporting calls for a specific user
1.620 albertel 10233: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10234: if ($qualifier eq 'value') {
10235: return $role;
10236: } elsif ($qualifier eq 'extent') {
10237: return $where;
10238: }
10239: # ----------------------------------------------------------------- user.domain
10240: } elsif ($space eq 'domain') {
1.218 albertel 10241: return $udom;
1.48 www 10242: # ------------------------------------------------------------------- user.name
10243: } elsif ($space eq 'name') {
1.218 albertel 10244: return $uname;
1.48 www 10245: # ---------------------------------------------------- Any other user namespace
1.29 www 10246: } else {
1.359 albertel 10247: my %reply;
10248: if (!$publicuser) {
10249: %reply=&get($space,[$qualifierrest],$udom,$uname);
10250: }
10251: return $reply{$qualifierrest};
1.48 www 10252: }
1.236 www 10253: } elsif ($realm eq 'query') {
10254: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10255: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10256: [$spacequalifierrest]);
1.620 albertel 10257: return $env{'form.'.$spacequalifierrest};
1.236 www 10258: } elsif ($realm eq 'request') {
1.48 www 10259: # ------------------------------------------------------------- request.browser
10260: if ($space eq 'browser') {
1.1145 bisitz 10261: return $env{'browser.'.$qualifier};
1.57 www 10262: # ------------------------------------------------------------ request.filename
10263: } else {
1.620 albertel 10264: return $env{'request.'.$spacequalifierrest};
1.29 www 10265: }
1.28 www 10266: } elsif ($realm eq 'course') {
1.48 www 10267: # ---------------------------------------------------------- course.description
1.620 albertel 10268: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10269: } elsif ($realm eq 'resource') {
1.165 www 10270:
1.620 albertel 10271: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10272: if (!$symbparm) { $symbparm=&symbread(); }
10273: }
1.693 albertel 10274:
1.1172.2.30 raeburn 10275: if ($qualifier eq '') {
10276: if ($space eq 'title') {
10277: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10278: return &gettitle($symbparm);
10279: }
1.693 albertel 10280:
1.1172.2.30 raeburn 10281: if ($space eq 'map') {
10282: my ($map) = &decode_symb($symbparm);
10283: return &symbread($map);
10284: }
10285: if ($space eq 'maptitle') {
10286: my ($map) = &decode_symb($symbparm);
10287: return &gettitle($map);
10288: }
10289: if ($space eq 'filename') {
10290: if ($symbparm) {
10291: return &clutter((&decode_symb($symbparm))[2]);
10292: }
10293: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10294: }
1.1172.2.30 raeburn 10295:
10296: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10297: if ($space eq 'visibleparts') {
10298: my $navmap = Apache::lonnavmaps::navmap->new();
10299: my $item;
10300: if (ref($navmap)) {
10301: my $res = $navmap->getBySymb($symbparm);
10302: my $parts = $res->parts();
10303: if (ref($parts) eq 'ARRAY') {
10304: $item = join(',',@{$parts});
10305: }
10306: undef($navmap);
10307: }
10308: return $item;
10309: }
10310: }
10311: }
1.693 albertel 10312:
10313: my ($section, $group, @groups);
1.593 albertel 10314: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 10315: if (($courseid eq '') && ($cid)) {
10316: $courseid = $cid;
10317: }
10318: if (($symbparm && $courseid) &&
10319: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10320:
1.218 albertel 10321: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10322:
1.60 www 10323: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10324: my $symbp=$symbparm;
1.735 albertel 10325: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10326:
10327: my $symbparm=$symbp.'.'.$spacequalifierrest;
10328: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10329:
1.620 albertel 10330: if (($env{'user.name'} eq $uname) &&
10331: ($env{'user.domain'} eq $udom)) {
10332: $section=$env{'request.course.sec'};
1.733 raeburn 10333: @groups = split(/:/,$env{'request.course.groups'});
10334: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10335: } else {
1.539 albertel 10336: if (! defined($usection)) {
1.551 albertel 10337: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10338: } else {
10339: $section = $usection;
10340: }
1.733 raeburn 10341: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10342: }
10343:
10344: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10345: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10346: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10347:
1.593 albertel 10348: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10349: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10350: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10351:
1.60 www 10352: # ----------------------------------------------------------- first, check user
1.624 albertel 10353:
10354: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10355: ([$courselevelr,'resource'],
10356: [$courselevelm,'map' ],
10357: [$courselevel, 'course' ]));
1.931 albertel 10358: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10359:
1.594 albertel 10360: # ------------------------------------------------ second, check some of course
1.684 raeburn 10361: my $coursereply;
1.691 raeburn 10362: if (@groups > 0) {
10363: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10364: $mapparm,$spacequalifierrest);
1.927 albertel 10365: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10366: }
1.96 www 10367:
1.684 raeburn 10368: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10369: $env{'course.'.$courseid.'.domain'},
10370: 'course',
10371: ([$seclevelr, 'resource'],
10372: [$seclevelm, 'map' ],
10373: [$seclevel, 'course' ],
10374: [$courselevelr,'resource']));
10375: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10376:
1.60 www 10377: # ------------------------------------------------------ third, check map parms
1.218 albertel 10378: my %parmhash=();
10379: my $thisparm='';
10380: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10381: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10382: &GDBM_READER(),0640)) {
1.218 albertel 10383: $thisparm=$parmhash{$symbparm};
10384: untie(%parmhash);
10385: }
1.927 albertel 10386: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10387: }
1.594 albertel 10388: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10389:
1.218 albertel 10390: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10391: my $filename;
10392: if (!$symbparm) { $symbparm=&symbread(); }
10393: if ($symbparm) {
1.409 www 10394: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10395: } else {
1.620 albertel 10396: $filename=$env{'request.filename'};
1.282 albertel 10397: }
10398: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10399: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10400: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10401: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10402:
1.927 albertel 10403: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10404: if ($symbparm && defined($courseid) &&
1.620 albertel 10405: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10406: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10407: $env{'course.'.$courseid.'.domain'},
10408: 'course',
1.927 albertel 10409: ([$courselevelm,'map' ],
10410: [$courselevel, 'course']));
10411: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10412: }
1.145 www 10413: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10414: unless ($space eq '0') {
1.336 albertel 10415: my @parts=split(/_/,$space);
10416: my $id=pop(@parts);
10417: my $part=join('_',@parts);
10418: if ($part eq '') { $part='0'; }
1.927 albertel 10419: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10420: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10421: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10422: }
1.395 albertel 10423: if ($recurse) { return undef; }
10424: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10425: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10426: # ---------------------------------------------------- Any other user namespace
10427: } elsif ($realm eq 'environment') {
10428: # ----------------------------------------------------------------- environment
1.620 albertel 10429: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10430: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10431: } else {
1.770 albertel 10432: if ($uname eq 'anonymous' && $udom eq '') {
10433: return '';
10434: }
1.219 albertel 10435: my %returnhash=&userenvironment($udom,$uname,
10436: $spacequalifierrest);
10437: return $returnhash{$spacequalifierrest};
10438: }
1.28 www 10439: } elsif ($realm eq 'system') {
1.48 www 10440: # ----------------------------------------------------------------- system.time
10441: if ($space eq 'time') {
10442: return time;
10443: }
1.696 albertel 10444: } elsif ($realm eq 'server') {
10445: # ----------------------------------------------------------------- system.time
10446: if ($space eq 'name') {
10447: return $ENV{'SERVER_NAME'};
10448: }
1.28 www 10449: }
1.48 www 10450: return '';
1.61 www 10451: }
10452:
1.927 albertel 10453: sub get_reply {
10454: my ($reply_value) = @_;
1.940 raeburn 10455: if (ref($reply_value) eq 'ARRAY') {
10456: if (wantarray) {
10457: return @$reply_value;
10458: }
10459: return $reply_value->[0];
10460: } else {
10461: return $reply_value;
1.927 albertel 10462: }
10463: }
10464:
1.691 raeburn 10465: sub check_group_parms {
10466: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10467: my @groupitems = ();
10468: my $resultitem;
1.927 albertel 10469: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10470: foreach my $group (@{$groups}) {
10471: foreach my $level (@levels) {
1.927 albertel 10472: my $item = $courseid.'.['.$group.'].'.$level->[0];
10473: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10474: }
10475: }
10476: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10477: $env{'course.'.$courseid.'.domain'},
10478: 'course',@groupitems);
10479: return $coursereply;
10480: }
10481:
10482: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10483: my ($courseid,@groups) = @_;
10484: @groups = sort(@groups);
1.691 raeburn 10485: return @groups;
10486: }
10487:
1.395 albertel 10488: sub packages_tab_default {
10489: my ($uri,$varname)=@_;
10490: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10491:
10492: my (@extension,@specifics,$do_default);
10493: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10494: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10495: if ($pack_type eq 'default') {
10496: $do_default=1;
10497: } elsif ($pack_type eq 'extension') {
10498: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10499: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10500: # only look at packages defaults for packages that this id is
1.738 albertel 10501: push(@specifics,[$package,$pack_type,$pack_part]);
10502: }
10503: }
10504: # first look for a package that matches the requested part id
10505: foreach my $package (@specifics) {
10506: my (undef,$pack_type,$pack_part)=@{$package};
10507: next if ($pack_part ne $part);
10508: if (defined($packagetab{"$pack_type&$name&default"})) {
10509: return $packagetab{"$pack_type&$name&default"};
10510: }
10511: }
10512: # look for any possible matching non extension_ package
10513: foreach my $package (@specifics) {
10514: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10515: if (defined($packagetab{"$pack_type&$name&default"})) {
10516: return $packagetab{"$pack_type&$name&default"};
10517: }
1.585 albertel 10518: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10519: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10520: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10521: }
10522: }
1.738 albertel 10523: # look for any posible extension_ match
10524: foreach my $package (@extension) {
10525: my ($package,$pack_type)=@{$package};
10526: if (defined($packagetab{"$pack_type&$name&default"})) {
10527: return $packagetab{"$pack_type&$name&default"};
10528: }
10529: if (defined($packagetab{$package."&$name&default"})) {
10530: return $packagetab{$package."&$name&default"};
10531: }
10532: }
10533: # look for a global default setting
10534: if ($do_default && defined($packagetab{"default&$name&default"})) {
10535: return $packagetab{"default&$name&default"};
10536: }
1.395 albertel 10537: return undef;
10538: }
10539:
1.334 albertel 10540: sub add_prefix_and_part {
10541: my ($prefix,$part)=@_;
10542: my $keyroot;
10543: if (defined($prefix) && $prefix !~ /^__/) {
10544: # prefix that has a part already
10545: $keyroot=$prefix;
10546: } elsif (defined($prefix)) {
10547: # prefix that is missing a part
10548: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10549: } else {
10550: # no prefix at all
10551: if (defined($part)) { $keyroot='_'.$part; }
10552: }
10553: return $keyroot;
10554: }
10555:
1.71 www 10556: # ---------------------------------------------------------------- Get metadata
10557:
1.599 albertel 10558: my %metaentry;
1.1070 www 10559: my %importedpartids;
1.71 www 10560: sub metadata {
1.176 www 10561: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10562: $uri=&declutter($uri);
1.288 albertel 10563: # if it is a non metadata possible uri return quickly
1.529 albertel 10564: if (($uri eq '') ||
10565: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 10566: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10567: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10568: return undef;
10569: }
1.1172.2.49 raeburn 10570: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10571: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10572: return undef;
1.288 albertel 10573: }
1.73 www 10574: my $filename=$uri;
10575: $uri=~s/\.meta$//;
1.172 www 10576: #
10577: # Is the metadata already cached?
1.177 www 10578: # Look at timestamp of caching
1.172 www 10579: # Everything is cached by the main uri, libraries are never directly cached
10580: #
1.428 albertel 10581: if (!defined($liburi)) {
1.599 albertel 10582: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10583: if (defined($cached)) { return $result->{':'.$what}; }
10584: }
10585: {
1.1069 www 10586: # Imported parts would go here
1.1070 www 10587: my %importedids=();
10588: my @origfileimportpartids=();
1.1069 www 10589: my $importedparts=0;
1.172 www 10590: #
10591: # Is this a recursive call for a library?
10592: #
1.599 albertel 10593: # if (! exists($metacache{$uri})) {
10594: # $metacache{$uri}={};
10595: # }
1.924 albertel 10596: my $cachetime = 60*60;
1.171 www 10597: if ($liburi) {
10598: $liburi=&declutter($liburi);
10599: $filename=$liburi;
1.401 bowersj2 10600: } else {
1.599 albertel 10601: &devalidate_cache_new('meta',$uri);
10602: undef(%metaentry);
1.401 bowersj2 10603: }
1.140 www 10604: my %metathesekeys=();
1.73 www 10605: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10606: my $metastring;
1.1140 www 10607: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10608: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10609: $metastring =
1.929 albertel 10610: &Apache::lonnet::ssi_body($which,
1.924 albertel 10611: ('grade_target' => 'meta'));
10612: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10613: } elsif (($uri !~ m -^(editupload)/-) &&
10614: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10615: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10616: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10617: $metastring=&getfile($file);
1.489 albertel 10618: }
1.208 albertel 10619: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10620: my $token;
1.140 www 10621: undef %metathesekeys;
1.71 www 10622: while ($token=$parser->get_token) {
1.339 albertel 10623: if ($token->[0] eq 'S') {
10624: if (defined($token->[2]->{'package'})) {
1.172 www 10625: #
10626: # This is a package - get package info
10627: #
1.339 albertel 10628: my $package=$token->[2]->{'package'};
10629: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10630: if (defined($token->[2]->{'id'})) {
10631: $keyroot.='_'.$token->[2]->{'id'};
10632: }
1.599 albertel 10633: if ($metaentry{':packages'}) {
10634: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10635: } else {
1.599 albertel 10636: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10637: }
1.736 albertel 10638: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10639: my $part=$keyroot;
10640: $part=~s/^\_//;
1.736 albertel 10641: if ($pack_entry=~/^\Q$package\E\&/ ||
10642: $pack_entry=~/^\Q$package\E_0\&/) {
10643: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10644: # ignore package.tab specified default values
10645: # here &package_tab_default() will fetch those
10646: if ($subp eq 'default') { next; }
1.736 albertel 10647: my $value=$packagetab{$pack_entry};
1.432 albertel 10648: my $unikey;
10649: if ($pack =~ /_0$/) {
10650: $unikey='parameter_0_'.$name;
10651: $part=0;
10652: } else {
10653: $unikey='parameter'.$keyroot.'_'.$name;
10654: }
1.339 albertel 10655: if ($subp eq 'display') {
10656: $value.=' [Part: '.$part.']';
10657: }
1.599 albertel 10658: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10659: $metathesekeys{$unikey}=1;
1.599 albertel 10660: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10661: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10662: }
1.599 albertel 10663: if (defined($metaentry{':'.$unikey.'.default'})) {
10664: $metaentry{':'.$unikey}=
10665: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10666: }
1.339 albertel 10667: }
10668: }
10669: } else {
1.172 www 10670: #
10671: # This is not a package - some other kind of start tag
1.339 albertel 10672: #
10673: my $entry=$token->[1];
1.1068 www 10674: my $unikey='';
1.175 www 10675:
1.339 albertel 10676: if ($entry eq 'import') {
1.175 www 10677: #
10678: # Importing a library here
1.339 albertel 10679: #
1.1067 www 10680: my $location=$parser->get_text('/import');
10681: my $dir=$filename;
10682: $dir=~s|[^/]*$||;
10683: $location=&filelocation($dir,$location);
1.1069 www 10684:
1.1068 www 10685: my $importmode=$token->[2]->{'importmode'};
10686: if ($importmode eq 'problem') {
1.1069 www 10687: # Import as problem/response
1.1068 www 10688: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10689: } elsif ($importmode eq 'part') {
10690: # Import as part(s)
1.1069 www 10691: $importedparts=1;
10692: # We need to get the original file and the imported file to get the part order correct
10693: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10694: # Load and inspect original file
1.1070 www 10695: if ($#origfileimportpartids<0) {
10696: undef(%importedpartids);
10697: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10698: my $origfile=&getfile($origfilelocation);
10699: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10700: }
10701:
1.1069 www 10702: # Load and inspect imported file
10703: my $impfile=&getfile($location);
10704: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10705: if ($#impfilepartids>=0) {
10706: # This problem had parts
1.1070 www 10707: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10708: } else {
10709: # Importing by turning a single problem into a problem part
10710: # It gets the import-tags ID as part-ID
10711: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10712: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10713: }
1.1068 www 10714: } else {
10715: # Normal import
10716: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10717: if (defined($token->[2]->{'id'})) {
10718: $unikey.='_'.$token->[2]->{'id'};
10719: }
1.1067 www 10720: }
10721:
1.339 albertel 10722: if ($depthcount<20) {
1.736 albertel 10723: my $metadata =
10724: &metadata($uri,'keys', $location,$unikey,
10725: $depthcount+1);
10726: foreach my $meta (split(',',$metadata)) {
10727: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10728: $metathesekeys{$meta}=1;
1.339 albertel 10729: }
1.1068 www 10730:
10731: }
1.1067 www 10732: } else {
10733: #
10734: # Not importing, some other kind of non-package, non-library start tag
10735: #
10736: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10737: if (defined($token->[2]->{'id'})) {
10738: $unikey.='_'.$token->[2]->{'id'};
10739: }
1.339 albertel 10740: if (defined($token->[2]->{'name'})) {
10741: $unikey.='_'.$token->[2]->{'name'};
10742: }
10743: $metathesekeys{$unikey}=1;
1.736 albertel 10744: foreach my $param (@{$token->[3]}) {
10745: $metaentry{':'.$unikey.'.'.$param} =
10746: $token->[2]->{$param};
1.339 albertel 10747: }
10748: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10749: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10750: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10751: # only ws inside the tag, and not in default, so use default
10752: # as value
1.599 albertel 10753: $metaentry{':'.$unikey}=$default;
1.908 albertel 10754: } elsif ( $internaltext =~ /\S/ ) {
10755: # something interesting inside the tag
10756: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10757: } else {
1.908 albertel 10758: # no interesting values, don't set a default
1.339 albertel 10759: }
1.172 www 10760: # end of not-a-package not-a-library import
1.339 albertel 10761: }
1.172 www 10762: # end of not-a-package start tag
1.339 albertel 10763: }
1.172 www 10764: # the next is the end of "start tag"
1.339 albertel 10765: }
10766: }
1.483 albertel 10767: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10768: $extension = lc($extension);
10769: if ($extension eq 'htm') { $extension='html'; }
10770:
1.737 albertel 10771: foreach my $key (keys(%packagetab)) {
1.483 albertel 10772: #no specific packages #how's our extension
10773: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10774: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10775: \%metathesekeys);
10776: }
1.883 albertel 10777:
10778: if (!exists($metaentry{':packages'})
10779: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10780: foreach my $key (keys(%packagetab)) {
1.483 albertel 10781: #no specific packages well let's get default then
10782: if ($key!~/^default&/) { next; }
1.488 albertel 10783: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10784: \%metathesekeys);
10785: }
10786: }
1.338 www 10787: # are there custom rights to evaluate
1.599 albertel 10788: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10789:
1.338 www 10790: #
10791: # Importing a rights file here
1.339 albertel 10792: #
10793: unless ($depthcount) {
1.599 albertel 10794: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10795: my $dir=$filename;
10796: $dir=~s|[^/]*$||;
10797: $location=&filelocation($dir,$location);
1.736 albertel 10798: my $rights_metadata =
10799: &metadata($uri,'keys',$location,'_rights',
10800: $depthcount+1);
10801: foreach my $rights (split(',',$rights_metadata)) {
10802: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10803: $metathesekeys{$rights}=1;
1.339 albertel 10804: }
10805: }
10806: }
1.737 albertel 10807: # uniqifiy package listing
10808: my %seen;
10809: my @uniq_packages =
10810: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10811: $metaentry{':packages'} = join(',',@uniq_packages);
10812:
1.1070 www 10813: if ($importedparts) {
10814: # We had imported parts and need to rebuild partorder
10815: $metaentry{':partorder'}='';
10816: $metathesekeys{'partorder'}=1;
10817: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10818: if ($origfileimportpartids[$index] eq 'part') {
10819: # original part, part of the problem
10820: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10821: } else {
10822: # we have imported parts at this position
10823: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10824: }
10825: }
10826: $metaentry{':partorder'}=~s/^\,//;
10827: }
10828:
1.737 albertel 10829: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10830: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 10831: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 10832: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10833: # this is the end of "was not already recently cached
1.71 www 10834: }
1.599 albertel 10835: return $metaentry{':'.$what};
1.261 albertel 10836: }
10837:
1.488 albertel 10838: sub metadata_create_package_def {
1.483 albertel 10839: my ($uri,$key,$package,$metathesekeys)=@_;
10840: my ($pack,$name,$subp)=split(/\&/,$key);
10841: if ($subp eq 'default') { next; }
10842:
1.599 albertel 10843: if (defined($metaentry{':packages'})) {
10844: $metaentry{':packages'}.=','.$package;
1.483 albertel 10845: } else {
1.599 albertel 10846: $metaentry{':packages'}=$package;
1.483 albertel 10847: }
10848: my $value=$packagetab{$key};
10849: my $unikey;
10850: $unikey='parameter_0_'.$name;
1.599 albertel 10851: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10852: $$metathesekeys{$unikey}=1;
1.599 albertel 10853: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10854: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10855: }
1.599 albertel 10856: if (defined($metaentry{':'.$unikey.'.default'})) {
10857: $metaentry{':'.$unikey}=
10858: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10859: }
10860: }
10861:
1.261 albertel 10862: sub metadata_generate_part0 {
10863: my ($metadata,$metacache,$uri) = @_;
10864: my %allnames;
1.737 albertel 10865: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10866: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10867: my $part=$$metacache{':'.$metakey.'.part'};
10868: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10869: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10870: $allnames{$name}=$part;
10871: }
10872: }
10873: }
10874: foreach my $name (keys(%allnames)) {
10875: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10876: my $key=":parameter_0_$name";
1.261 albertel 10877: $$metacache{"$key.part"}='0';
10878: $$metacache{"$key.name"}=$name;
1.428 albertel 10879: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10880: $allnames{$name}.'_'.$name.
10881: '.type'};
1.428 albertel 10882: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10883: '.display'};
1.644 www 10884: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10885: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10886: $$metacache{"$key.display"}=$olddis;
10887: }
1.71 www 10888: }
10889:
1.764 albertel 10890: # ------------------------------------------------------ Devalidate title cache
10891:
10892: sub devalidate_title_cache {
10893: my ($url)=@_;
10894: if (!$env{'request.course.id'}) { return; }
10895: my $symb=&symbread($url);
10896: if (!$symb) { return; }
10897: my $key=$env{'request.course.id'}."\0".$symb;
10898: &devalidate_cache_new('title',$key);
10899: }
10900:
1.1014 droeschl 10901: # ------------------------------------------------- Get the title of a course
10902:
10903: sub current_course_title {
10904: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10905: }
1.301 www 10906: # ------------------------------------------------- Get the title of a resource
10907:
10908: sub gettitle {
10909: my $urlsymb=shift;
10910: my $symb=&symbread($urlsymb);
1.534 albertel 10911: if ($symb) {
1.620 albertel 10912: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10913: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10914: if (defined($cached)) {
10915: return $result;
10916: }
1.534 albertel 10917: my ($map,$resid,$url)=&decode_symb($symb);
10918: my $title='';
1.907 albertel 10919: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10920: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10921: } else {
10922: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10923: &GDBM_READER(),0640)) {
10924: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10925: $title=$bighash{'title_'.$mapid.'.'.$resid};
10926: untie(%bighash);
10927: }
1.534 albertel 10928: }
10929: $title=~s/\&colon\;/\:/gs;
10930: if ($title) {
1.1159 www 10931: # Remember both $symb and $title for dynamic metadata
10932: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10933: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10934: # Cache this title and then return it
1.599 albertel 10935: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10936: }
10937: $urlsymb=$url;
10938: }
10939: my $title=&metadata($urlsymb,'title');
10940: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10941: return $title;
1.301 www 10942: }
1.613 albertel 10943:
1.614 albertel 10944: sub get_slot {
10945: my ($which,$cnum,$cdom)=@_;
10946: if (!$cnum || !$cdom) {
1.790 albertel 10947: (undef,my $courseid)=&whichuser();
1.620 albertel 10948: $cdom=$env{'course.'.$courseid.'.domain'};
10949: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10950: }
1.703 albertel 10951: my $key=join("\0",'slots',$cdom,$cnum,$which);
10952: my %slotinfo;
10953: if (exists($remembered{$key})) {
10954: $slotinfo{$which} = $remembered{$key};
10955: } else {
10956: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10957: &Apache::lonhomework::showhash(%slotinfo);
10958: my ($tmp)=keys(%slotinfo);
10959: if ($tmp=~/^error:/) { return (); }
10960: $remembered{$key} = $slotinfo{$which};
10961: }
1.616 albertel 10962: if (ref($slotinfo{$which}) eq 'HASH') {
10963: return %{$slotinfo{$which}};
10964: }
10965: return $slotinfo{$which};
1.614 albertel 10966: }
1.1150 raeburn 10967:
10968: sub get_reservable_slots {
10969: my ($cnum,$cdom,$uname,$udom) = @_;
10970: my $now = time;
10971: my $reservable_info;
10972: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10973: if (exists($remembered{$key})) {
10974: $reservable_info = $remembered{$key};
10975: } else {
10976: my %resv;
10977: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10978: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10979: $reservable_info = \%resv;
10980: $remembered{$key} = $reservable_info;
10981: }
10982: return $reservable_info;
10983: }
10984:
10985: sub get_course_slots {
10986: my ($cnum,$cdom) = @_;
10987: my $hashid=$cnum.':'.$cdom;
10988: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10989: if (defined($cached)) {
10990: if (ref($result) eq 'HASH') {
10991: return %{$result};
10992: }
10993: } else {
10994: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10995: my ($tmp) = keys(%slots);
10996: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 10997: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10998: return %slots;
10999: }
11000: }
11001: return;
11002: }
11003:
11004: sub devalidate_slots_cache {
11005: my ($cnum,$cdom)=@_;
11006: my $hashid=$cnum.':'.$cdom;
11007: &devalidate_cache_new('allslots',$hashid);
11008: }
11009:
1.1172.2.8 raeburn 11010: sub get_coursechange {
11011: my ($cdom,$cnum) = @_;
11012: if ($cdom eq '' || $cnum eq '') {
11013: return unless ($env{'request.course.id'});
11014: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11015: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11016: }
11017: my $hashid=$cdom.'_'.$cnum;
11018: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11019: if ((defined($cached)) && ($change ne '')) {
11020: return $change;
11021: } else {
11022: my %crshash;
11023: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11024: if ($crshash{'internal.contentchange'} eq '') {
11025: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11026: if ($change eq '') {
11027: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11028: $change = $crshash{'internal.created'};
11029: }
11030: } else {
11031: $change = $crshash{'internal.contentchange'};
11032: }
11033: my $cachetime = 600;
11034: &do_cache_new('crschange',$hashid,$change,$cachetime);
11035: }
11036: return $change;
11037: }
11038:
11039: sub devalidate_coursechange_cache {
11040: my ($cnum,$cdom)=@_;
11041: my $hashid=$cnum.':'.$cdom;
11042: &devalidate_cache_new('crschange',$hashid);
11043: }
11044:
1.31 www 11045: # ------------------------------------------------- Update symbolic store links
11046:
11047: sub symblist {
11048: my ($mapname,%newhash)=@_;
1.438 www 11049: $mapname=&deversion(&declutter($mapname));
1.31 www 11050: my %hash;
1.620 albertel 11051: if (($env{'request.course.fn'}) && (%newhash)) {
11052: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11053: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11054: foreach my $url (keys(%newhash)) {
1.711 albertel 11055: next if ($url eq 'last_known'
11056: && $env{'form.no_update_last_known'});
11057: $hash{declutter($url)}=&encode_symb($mapname,
11058: $newhash{$url}->[1],
11059: $newhash{$url}->[0]);
1.191 harris41 11060: }
1.31 www 11061: if (untie(%hash)) {
11062: return 'ok';
11063: }
11064: }
11065: }
11066: return 'error';
1.212 www 11067: }
11068:
11069: # --------------------------------------------------------------- Verify a symb
11070:
11071: sub symbverify {
1.1172.2.11 raeburn 11072: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11073: my $thisfn=$thisurl;
1.439 www 11074: $thisfn=&declutter($thisfn);
1.215 www 11075: # direct jump to resource in page or to a sequence - will construct own symbs
11076: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11077: # check URL part
1.409 www 11078: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11079:
1.431 www 11080: unless ($url eq $thisfn) { return 0; }
1.213 www 11081:
1.216 www 11082: $symb=&symbclean($symb);
1.510 www 11083: $thisurl=&deversion($thisurl);
1.439 www 11084: $thisfn=&deversion($thisfn);
1.213 www 11085:
11086: my %bighash;
11087: my $okay=0;
1.431 www 11088:
1.620 albertel 11089: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11090: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 11091: my $noclutter;
1.1032 raeburn 11092: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11093: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 11094: if ($map =~ m{^uploaded/.+\.page$}) {
11095: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11096: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11097: $noclutter = 1;
11098: }
11099: }
11100: my $ids;
11101: if ($noclutter) {
11102: $ids=$bighash{'ids_'.$thisurl};
11103: } else {
11104: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11105: }
1.1102 raeburn 11106: unless ($ids) {
1.1172.2.13 raeburn 11107: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 11108: $ids=$bighash{$idkey};
1.216 www 11109: }
11110: if ($ids) {
11111: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 11112: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
11113: $symb =~ s/\?.+$//;
11114: }
1.800 albertel 11115: foreach my $id (split(/\,/,$ids)) {
11116: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11117: if (
11118: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 11119: eq $symb) {
1.1172.2.11 raeburn 11120: if (ref($encstate)) {
11121: $$encstate = $bighash{'encrypted_'.$id};
11122: }
1.1172.2.13 raeburn 11123: if (($env{'request.role.adv'}) ||
11124: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 11125: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 11126: $okay=1;
11127: last;
11128: }
11129: }
11130: }
1.216 www 11131: }
1.213 www 11132: untie(%bighash);
11133: }
11134: return $okay;
1.31 www 11135: }
11136:
1.210 www 11137: # --------------------------------------------------------------- Clean-up symb
11138:
11139: sub symbclean {
11140: my $symb=shift;
1.568 albertel 11141: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11142: # remove version from map
11143: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11144:
1.210 www 11145: # remove version from URL
11146: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11147:
1.507 www 11148: # remove wrapper
11149:
1.510 www 11150: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11151: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11152: return $symb;
1.409 www 11153: }
11154:
11155: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11156:
11157: sub encode_symb {
11158: my ($map,$resid,$url)=@_;
11159: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11160: }
1.409 www 11161:
11162: sub decode_symb {
1.568 albertel 11163: my $symb=shift;
11164: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11165: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11166: return (&fixversion($map),$resid,&fixversion($url));
11167: }
11168:
11169: sub fixversion {
11170: my $fn=shift;
1.609 banghart 11171: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11172: my %bighash;
11173: my $uri=&clutter($fn);
1.620 albertel 11174: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11175: # is this cached?
1.599 albertel 11176: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11177: if (defined($cached)) { return $result; }
11178: # unfortunately not cached, or expired
1.620 albertel 11179: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11180: &GDBM_READER(),0640)) {
11181: if ($bighash{'version_'.$uri}) {
11182: my $version=$bighash{'version_'.$uri};
1.444 www 11183: unless (($version eq 'mostrecent') ||
11184: ($version==&getversion($uri))) {
1.440 www 11185: $uri=~s/\.(\w+)$/\.$version\.$1/;
11186: }
11187: }
11188: untie %bighash;
1.413 www 11189: }
1.599 albertel 11190: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11191: }
11192:
11193: sub deversion {
11194: my $url=shift;
11195: $url=~s/\.\d+\.(\w+)$/\.$1/;
11196: return $url;
1.210 www 11197: }
11198:
1.31 www 11199: # ------------------------------------------------------ Return symb list entry
11200:
11201: sub symbread {
1.1172.2.66 raeburn 11202: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54 raeburn 11203: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66 raeburn 11204: if (defined($env{$cache_str})) {
11205: if ($ignorecachednull) {
11206: return $env{$cache_str} unless ($env{$cache_str} eq '');
11207: } else {
11208: return $env{$cache_str};
11209: }
11210: }
1.242 www 11211: # no filename provided? try from environment
1.1172.2.54 raeburn 11212: unless ($thisfn) {
1.620 albertel 11213: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 11214: return $env{$cache_str}=&symbclean($env{'request.symb'});
11215: }
11216: $thisfn=$env{'request.filename'};
1.44 www 11217: }
1.569 albertel 11218: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11219: # is that filename actually a symb? Verify, clean, and return
11220: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11221: if (&symbverify($thisfn,$1)) {
1.620 albertel 11222: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11223: }
1.242 www 11224: }
1.44 www 11225: $thisfn=declutter($thisfn);
1.31 www 11226: my %hash;
1.37 www 11227: my %bighash;
11228: my $syval='';
1.620 albertel 11229: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11230: my $targetfn = $thisfn;
1.609 banghart 11231: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11232: $targetfn = 'adm/wrapper/'.$thisfn;
11233: }
1.687 albertel 11234: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11235: $targetfn=$1;
11236: }
1.620 albertel 11237: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11238: &GDBM_READER(),0640)) {
1.481 raeburn 11239: $syval=$hash{$targetfn};
1.37 www 11240: untie(%hash);
11241: }
11242: # ---------------------------------------------------------- There was an entry
11243: if ($syval) {
1.601 albertel 11244: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11245: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11246: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11247: #return $env{$cache_str}='';
1.601 albertel 11248: #}
11249: #$syval.=$1;
11250: #}
1.37 www 11251: } else {
11252: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11253: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11254: &GDBM_READER(),0640)) {
1.37 www 11255: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11256: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11257: unless ($ids) {
11258: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11259: }
11260: unless ($ids) {
11261: # alias?
11262: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11263: }
1.37 www 11264: if ($ids) {
11265: # ------------------------------------------------------------------- Has ID(s)
11266: my @possibilities=split(/\,/,$ids);
1.39 www 11267: if ($#possibilities==0) {
11268: # ----------------------------------------------- There is only one possibility
1.37 www 11269: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11270: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11271: $resid,$thisfn);
1.1172.2.66 raeburn 11272: if (ref($possibles) eq 'HASH') {
11273: $possibles->{$syval} = 1;
11274: }
11275: if ($checkforblock) {
11276: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11277: if (@blockers) {
11278: $syval = '';
11279: return;
11280: }
11281: }
11282: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11283: # ------------------------------------------ There is more than one possibility
11284: my $realpossible=0;
1.800 albertel 11285: foreach my $id (@possibilities) {
11286: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 11287: my $canaccess;
11288: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11289: $canaccess = 1;
11290: } else {
11291: $canaccess = &allowed('bre',$file);
11292: }
11293: if ($canaccess) {
11294: my ($mapid,$resid)=split(/\./,$id);
11295: if ($bighash{'map_type_'.$mapid} ne 'page') {
11296: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11297: $resid,$thisfn);
11298: if (ref($possibles) eq 'HASH') {
11299: $possibles->{$syval} = 1;
11300: }
11301: if ($checkforblock) {
11302: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11303: unless (@blockers > 0) {
11304: $syval = $poss_syval;
11305: $realpossible++;
11306: }
11307: } else {
11308: $syval = $poss_syval;
11309: $realpossible++;
11310: }
11311: }
1.39 www 11312: }
1.191 harris41 11313: }
1.39 www 11314: if ($realpossible!=1) { $syval=''; }
1.249 www 11315: } else {
11316: $syval='';
1.37 www 11317: }
11318: }
1.1172.2.66 raeburn 11319: untie(%bighash);
1.481 raeburn 11320: }
1.31 www 11321: }
1.62 www 11322: if ($syval) {
1.620 albertel 11323: return $env{$cache_str}=$syval;
1.62 www 11324: }
1.31 www 11325: }
1.949 raeburn 11326: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11327: return $env{$cache_str}='';
1.31 www 11328: }
11329:
11330: # ---------------------------------------------------------- Return random seed
11331:
1.32 www 11332: sub numval {
11333: my $txt=shift;
11334: $txt=~tr/A-J/0-9/;
11335: $txt=~tr/a-j/0-9/;
11336: $txt=~tr/K-T/0-9/;
11337: $txt=~tr/k-t/0-9/;
11338: $txt=~tr/U-Z/0-5/;
11339: $txt=~tr/u-z/0-5/;
11340: $txt=~s/\D//g;
1.564 albertel 11341: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11342: return int($txt);
1.368 albertel 11343: }
11344:
1.484 albertel 11345: sub numval2 {
11346: my $txt=shift;
11347: $txt=~tr/A-J/0-9/;
11348: $txt=~tr/a-j/0-9/;
11349: $txt=~tr/K-T/0-9/;
11350: $txt=~tr/k-t/0-9/;
11351: $txt=~tr/U-Z/0-5/;
11352: $txt=~tr/u-z/0-5/;
11353: $txt=~s/\D//g;
11354: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11355: my $total;
11356: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11357: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11358: return int($total);
11359: }
11360:
1.575 albertel 11361: sub numval3 {
11362: use integer;
11363: my $txt=shift;
11364: $txt=~tr/A-J/0-9/;
11365: $txt=~tr/a-j/0-9/;
11366: $txt=~tr/K-T/0-9/;
11367: $txt=~tr/k-t/0-9/;
11368: $txt=~tr/U-Z/0-5/;
11369: $txt=~tr/u-z/0-5/;
11370: $txt=~s/\D//g;
11371: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11372: my $total;
11373: foreach my $val (@txts) { $total+=$val; }
11374: if ($_64bit) { $total=(($total<<32)>>32); }
11375: return $total;
11376: }
11377:
1.675 albertel 11378: sub digest {
11379: my ($data)=@_;
11380: my $digest=&Digest::MD5::md5($data);
11381: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11382: my ($e,$f);
11383: {
11384: use integer;
11385: $e=($a+$b);
11386: $f=($c+$d);
11387: if ($_64bit) {
11388: $e=(($e<<32)>>32);
11389: $f=(($f<<32)>>32);
11390: }
11391: }
11392: if (wantarray) {
11393: return ($e,$f);
11394: } else {
11395: my $g;
11396: {
11397: use integer;
11398: $g=($e+$f);
11399: if ($_64bit) {
11400: $g=(($g<<32)>>32);
11401: }
11402: }
11403: return $g;
11404: }
11405: }
11406:
1.368 albertel 11407: sub latest_rnd_algorithm_id {
1.675 albertel 11408: return '64bit5';
1.366 albertel 11409: }
1.32 www 11410:
1.503 albertel 11411: sub get_rand_alg {
11412: my ($courseid)=@_;
1.790 albertel 11413: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11414: if ($courseid) {
1.620 albertel 11415: return $env{"course.$courseid.rndseed"};
1.503 albertel 11416: }
11417: return &latest_rnd_algorithm_id();
11418: }
11419:
1.562 albertel 11420: sub validCODE {
11421: my ($CODE)=@_;
11422: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11423: return 0;
11424: }
11425:
1.491 albertel 11426: sub getCODE {
1.620 albertel 11427: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11428: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11429: defined($Apache::lonhomework::parsing_a_task) ) &&
11430: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11431: return $Apache::lonhomework::history{'resource.CODE'};
11432: }
11433: return undef;
11434: }
1.1133 foxr 11435: #
11436: # Determines the random seed for a specific context:
11437: #
11438: # parameters:
11439: # symb - in course context the symb for the seed.
11440: # course_id - The course id of the form domain_coursenum.
11441: # domain - Domain for the user.
11442: # course - Course for the user.
11443: # cenv - environment of the course.
11444: #
11445: # NOTE:
11446: # All parameters are picked out of the environment if missing
11447: # or not defined.
11448: # If a symb cannot be determined the current time is used instead.
11449: #
11450: # For a given well defined symb, courside, domain, username,
11451: # and course environment, the seed is reproducible.
11452: #
1.31 www 11453: sub rndseed {
1.1133 foxr 11454: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11455: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11456: if (!defined($symb)) {
1.366 albertel 11457: unless ($symb=$wsymb) { return time; }
11458: }
1.1146 foxr 11459: if (!defined $courseid) {
11460: $courseid=$wcourseid;
11461: }
11462: if (!defined $domain) { $domain=$wdomain; }
11463: if (!defined $username) { $username=$wusername }
1.1133 foxr 11464:
11465: my $which;
11466: if (defined($cenv->{'rndseed'})) {
11467: $which = $cenv->{'rndseed'};
11468: } else {
11469: $which =&get_rand_alg($courseid);
11470: }
1.491 albertel 11471: if (defined(&getCODE())) {
1.675 albertel 11472: if ($which eq '64bit5') {
11473: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11474: } elsif ($which eq '64bit4') {
1.575 albertel 11475: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11476: } else {
11477: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11478: }
1.675 albertel 11479: } elsif ($which eq '64bit5') {
11480: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11481: } elsif ($which eq '64bit4') {
11482: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11483: } elsif ($which eq '64bit3') {
11484: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11485: } elsif ($which eq '64bit2') {
11486: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11487: } elsif ($which eq '64bit') {
11488: return &rndseed_64bit($symb,$courseid,$domain,$username);
11489: }
11490: return &rndseed_32bit($symb,$courseid,$domain,$username);
11491: }
11492:
11493: sub rndseed_32bit {
11494: my ($symb,$courseid,$domain,$username)=@_;
11495: {
11496: use integer;
11497: my $symbchck=unpack("%32C*",$symb) << 27;
11498: my $symbseed=numval($symb) << 22;
11499: my $namechck=unpack("%32C*",$username) << 17;
11500: my $nameseed=numval($username) << 12;
11501: my $domainseed=unpack("%32C*",$domain) << 7;
11502: my $courseseed=unpack("%32C*",$courseid);
11503: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11504: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11505: #&logthis("rndseed :$num:$symb");
1.564 albertel 11506: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11507: return $num;
11508: }
11509: }
11510:
11511: sub rndseed_64bit {
11512: my ($symb,$courseid,$domain,$username)=@_;
11513: {
11514: use integer;
11515: my $symbchck=unpack("%32S*",$symb) << 21;
11516: my $symbseed=numval($symb) << 10;
11517: my $namechck=unpack("%32S*",$username);
11518:
11519: my $nameseed=numval($username) << 21;
11520: my $domainseed=unpack("%32S*",$domain) << 10;
11521: my $courseseed=unpack("%32S*",$courseid);
11522:
11523: my $num1=$symbchck+$symbseed+$namechck;
11524: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11525: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11526: #&logthis("rndseed :$num:$symb");
1.564 albertel 11527: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11528: return "$num1,$num2";
1.155 albertel 11529: }
1.366 albertel 11530: }
11531:
1.443 albertel 11532: sub rndseed_64bit2 {
11533: my ($symb,$courseid,$domain,$username)=@_;
11534: {
11535: use integer;
11536: # strings need to be an even # of cahracters long, it it is odd the
11537: # last characters gets thrown away
11538: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11539: my $symbseed=numval($symb) << 10;
11540: my $namechck=unpack("%32S*",$username.' ');
11541:
11542: my $nameseed=numval($username) << 21;
1.501 albertel 11543: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11544: my $courseseed=unpack("%32S*",$courseid.' ');
11545:
11546: my $num1=$symbchck+$symbseed+$namechck;
11547: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11548: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11549: #&logthis("rndseed :$num:$symb");
1.803 albertel 11550: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11551: return "$num1,$num2";
11552: }
11553: }
11554:
11555: sub rndseed_64bit3 {
11556: my ($symb,$courseid,$domain,$username)=@_;
11557: {
11558: use integer;
11559: # strings need to be an even # of cahracters long, it it is odd the
11560: # last characters gets thrown away
11561: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11562: my $symbseed=numval2($symb) << 10;
11563: my $namechck=unpack("%32S*",$username.' ');
11564:
11565: my $nameseed=numval2($username) << 21;
1.443 albertel 11566: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11567: my $courseseed=unpack("%32S*",$courseid.' ');
11568:
11569: my $num1=$symbchck+$symbseed+$namechck;
11570: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11571: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11572: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11573: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11574:
1.503 albertel 11575: return "$num1:$num2";
1.443 albertel 11576: }
11577: }
11578:
1.575 albertel 11579: sub rndseed_64bit4 {
11580: my ($symb,$courseid,$domain,$username)=@_;
11581: {
11582: use integer;
11583: # strings need to be an even # of cahracters long, it it is odd the
11584: # last characters gets thrown away
11585: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11586: my $symbseed=numval3($symb) << 10;
11587: my $namechck=unpack("%32S*",$username.' ');
11588:
11589: my $nameseed=numval3($username) << 21;
11590: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11591: my $courseseed=unpack("%32S*",$courseid.' ');
11592:
11593: my $num1=$symbchck+$symbseed+$namechck;
11594: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11595: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11596: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11597: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11598:
1.575 albertel 11599: return "$num1:$num2";
11600: }
11601: }
11602:
1.675 albertel 11603: sub rndseed_64bit5 {
11604: my ($symb,$courseid,$domain,$username)=@_;
11605: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11606: return "$num1:$num2";
11607: }
11608:
1.366 albertel 11609: sub rndseed_CODE_64bit {
11610: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11611: {
1.366 albertel 11612: use integer;
1.443 albertel 11613: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11614: my $symbseed=numval2($symb);
1.491 albertel 11615: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11616: my $CODEseed=numval(&getCODE());
1.443 albertel 11617: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11618: my $num1=$symbseed+$CODEchck;
11619: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11620: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11621: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11622: if ($_64bit) { $num1=(($num1<<32)>>32); }
11623: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11624: return "$num1:$num2";
1.366 albertel 11625: }
11626: }
11627:
1.575 albertel 11628: sub rndseed_CODE_64bit4 {
11629: my ($symb,$courseid,$domain,$username)=@_;
11630: {
11631: use integer;
11632: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11633: my $symbseed=numval3($symb);
11634: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11635: my $CODEseed=numval3(&getCODE());
11636: my $courseseed=unpack("%32S*",$courseid.' ');
11637: my $num1=$symbseed+$CODEchck;
11638: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11639: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11640: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11641: if ($_64bit) { $num1=(($num1<<32)>>32); }
11642: if ($_64bit) { $num2=(($num2<<32)>>32); }
11643: return "$num1:$num2";
11644: }
11645: }
11646:
1.675 albertel 11647: sub rndseed_CODE_64bit5 {
11648: my ($symb,$courseid,$domain,$username)=@_;
11649: my $code = &getCODE();
11650: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11651: return "$num1:$num2";
11652: }
11653:
1.366 albertel 11654: sub setup_random_from_rndseed {
11655: my ($rndseed)=@_;
1.503 albertel 11656: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 11657: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11658: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11659: &Math::Random::random_set_seed_from_phrase($rndseed);
11660: } else {
11661: &Math::Random::random_set_seed($num1,$num2);
11662: }
1.366 albertel 11663: } else {
11664: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11665: }
1.36 albertel 11666: }
11667:
1.474 albertel 11668: sub latest_receipt_algorithm_id {
1.835 albertel 11669: return 'receipt3';
1.474 albertel 11670: }
11671:
1.480 www 11672: sub recunique {
11673: my $fucourseid=shift;
11674: my $unique;
1.835 albertel 11675: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11676: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11677: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11678: } else {
11679: $unique=$perlvar{'lonReceipt'};
11680: }
11681: return unpack("%32C*",$unique);
11682: }
11683:
11684: sub recprefix {
11685: my $fucourseid=shift;
11686: my $prefix;
1.835 albertel 11687: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11688: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11689: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11690: } else {
11691: $prefix=$perlvar{'lonHostID'};
11692: }
11693: return unpack("%32C*",$prefix);
11694: }
11695:
1.76 www 11696: sub ireceipt {
1.474 albertel 11697: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11698:
11699: my $return =&recprefix($fucourseid).'-';
11700:
11701: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11702: $env{'request.state'} eq 'construct') {
11703: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11704: return $return;
11705: }
11706:
1.76 www 11707: my $cuname=unpack("%32C*",$funame);
11708: my $cudom=unpack("%32C*",$fudom);
11709: my $cucourseid=unpack("%32C*",$fucourseid);
11710: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11711: my $cunique=&recunique($fucourseid);
1.474 albertel 11712: my $cpart=unpack("%32S*",$part);
1.835 albertel 11713: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11714:
1.790 albertel 11715: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11716:
11717: $return.= ($cunique%$cuname+
11718: $cunique%$cudom+
11719: $cusymb%$cuname+
11720: $cusymb%$cudom+
11721: $cucourseid%$cuname+
11722: $cucourseid%$cudom+
11723: $cpart%$cuname+
11724: $cpart%$cudom);
11725: } else {
11726: $return.= ($cunique%$cuname+
11727: $cunique%$cudom+
11728: $cusymb%$cuname+
11729: $cusymb%$cudom+
11730: $cucourseid%$cuname+
11731: $cucourseid%$cudom);
11732: }
11733: return $return;
1.76 www 11734: }
11735:
11736: sub receipt {
1.474 albertel 11737: my ($part)=@_;
1.790 albertel 11738: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11739: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11740: }
1.260 ng 11741:
1.790 albertel 11742: sub whichuser {
11743: my ($passedsymb)=@_;
11744: my ($symb,$courseid,$domain,$name,$publicuser);
11745: if (defined($env{'form.grade_symb'})) {
11746: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11747: my $allowed=&allowed('vgr',$tmp_courseid);
11748: if (!$allowed &&
11749: exists($env{'request.course.sec'}) &&
11750: $env{'request.course.sec'} !~ /^\s*$/) {
11751: $allowed=&allowed('vgr',$tmp_courseid.
11752: '/'.$env{'request.course.sec'});
11753: }
11754: if ($allowed) {
11755: ($symb)=&get_env_multiple('form.grade_symb');
11756: $courseid=$tmp_courseid;
11757: ($domain)=&get_env_multiple('form.grade_domain');
11758: ($name)=&get_env_multiple('form.grade_username');
11759: return ($symb,$courseid,$domain,$name,$publicuser);
11760: }
11761: }
11762: if (!$passedsymb) {
11763: $symb=&symbread();
11764: } else {
11765: $symb=$passedsymb;
11766: }
11767: $courseid=$env{'request.course.id'};
11768: $domain=$env{'user.domain'};
11769: $name=$env{'user.name'};
11770: if ($name eq 'public' && $domain eq 'public') {
11771: if (!defined($env{'form.username'})) {
11772: $env{'form.username'}.=time.rand(10000000);
11773: }
11774: $name.=$env{'form.username'};
11775: }
11776: return ($symb,$courseid,$domain,$name,$publicuser);
11777:
11778: }
11779:
1.36 albertel 11780: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11781: # returns either the contents of the file or
11782: # -1 if the file doesn't exist
1.481 raeburn 11783: #
11784: # if the target is a file that was uploaded via DOCS,
11785: # a check will be made to see if a current copy exists on the local server,
11786: # if it does this will be served, otherwise a copy will be retrieved from
11787: # the home server for the course and stored in /home/httpd/html/userfiles on
11788: # the local server.
1.472 albertel 11789:
1.36 albertel 11790: sub getfile {
1.538 albertel 11791: my ($file) = @_;
1.609 banghart 11792: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11793: &repcopy($file);
11794: return &readfile($file);
11795: }
11796:
11797: sub repcopy_userfile {
11798: my ($file)=@_;
1.1142 raeburn 11799: my $londocroot = $perlvar{'lonDocRoot'};
11800: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11801: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11802: my ($cdom,$cnum,$filename) =
1.811 albertel 11803: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11804: my $uri="/uploaded/$cdom/$cnum/$filename";
11805: if (-e "$file") {
1.828 www 11806: # we already have a local copy, check it out
1.538 albertel 11807: my @fileinfo = stat($file);
1.828 www 11808: my $rtncode;
11809: my $info;
1.538 albertel 11810: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11811: if ($lwpresp ne 'ok') {
1.828 www 11812: # there is no such file anymore, even though we had a local copy
1.482 albertel 11813: if ($rtncode eq '404') {
1.538 albertel 11814: unlink($file);
1.482 albertel 11815: }
11816: return -1;
11817: }
11818: if ($info < $fileinfo[9]) {
1.828 www 11819: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11820: return 'ok';
1.828 www 11821: } else {
11822: # the file is outdated, get rid of it
11823: unlink($file);
1.482 albertel 11824: }
1.828 www 11825: }
11826: # one way or the other, at this point, we don't have the file
11827: # construct the correct path for the file
11828: my @parts = ($cdom,$cnum);
11829: if ($filename =~ m|^(.+)/[^/]+$|) {
11830: push @parts, split(/\//,$1);
11831: }
11832: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11833: foreach my $part (@parts) {
11834: $path .= '/'.$part;
11835: if (!-e $path) {
11836: mkdir($path,0770);
1.482 albertel 11837: }
11838: }
1.828 www 11839: # now the path exists for sure
11840: # get a user agent
11841: my $ua=new LWP::UserAgent;
11842: my $transferfile=$file.'.in.transfer';
11843: # FIXME: this should flock
11844: if (-e $transferfile) { return 'ok'; }
11845: my $request;
11846: $uri=~s/^\///;
1.980 raeburn 11847: my $homeserver = &homeserver($cnum,$cdom);
11848: my $protocol = $protocol{$homeserver};
11849: $protocol = 'http' if ($protocol ne 'https');
11850: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11851: my $response=$ua->request($request,$transferfile);
11852: # did it work?
11853: if ($response->is_error()) {
11854: unlink($transferfile);
11855: &logthis("Userfile repcopy failed for $uri");
11856: return -1;
11857: }
11858: # worked, rename the transfer file
11859: rename($transferfile,$file);
1.607 raeburn 11860: return 'ok';
1.481 raeburn 11861: }
11862:
1.517 albertel 11863: sub tokenwrapper {
11864: my $uri=shift;
1.980 raeburn 11865: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11866: $uri=~s|^/||;
1.620 albertel 11867: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11868: my $token=$1;
1.552 albertel 11869: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11870: if ($udom && $uname && $file) {
11871: $file=~s|(\?\.*)*$||;
1.949 raeburn 11872: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11873: my $homeserver = &homeserver($uname,$udom);
11874: my $protocol = $protocol{$homeserver};
11875: $protocol = 'http' if ($protocol ne 'https');
11876: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11877: (($uri=~/\?/)?'&':'?').'token='.$token.
11878: '&tokenissued='.$perlvar{'lonHostID'};
11879: } else {
11880: return '/adm/notfound.html';
11881: }
11882: }
11883:
1.828 www 11884: # call with reqtype HEAD: get last modification time
11885: # call with reqtype GET: get the file contents
11886: # Do not call this with reqtype GET for large files! It loads everything into memory
11887: #
1.481 raeburn 11888: sub getuploaded {
11889: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11890: $uri=~s/^\///;
1.980 raeburn 11891: my $homeserver = &homeserver($cnum,$cdom);
11892: my $protocol = $protocol{$homeserver};
11893: $protocol = 'http' if ($protocol ne 'https');
11894: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11895: my $ua=new LWP::UserAgent;
11896: my $request=new HTTP::Request($reqtype,$uri);
11897: my $response=$ua->request($request);
11898: $$rtncode = $response->code;
1.482 albertel 11899: if (! $response->is_success()) {
11900: return 'failed';
11901: }
11902: if ($reqtype eq 'HEAD') {
1.486 www 11903: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11904: } elsif ($reqtype eq 'GET') {
11905: $$info = $response->content;
1.472 albertel 11906: }
1.482 albertel 11907: return 'ok';
1.36 albertel 11908: }
11909:
1.481 raeburn 11910: sub readfile {
11911: my $file = shift;
11912: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11913: my $fh;
11914: open($fh,"<$file");
11915: my $a='';
1.800 albertel 11916: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11917: return $a;
11918: }
11919:
1.36 albertel 11920: sub filelocation {
1.590 banghart 11921: my ($dir,$file) = @_;
11922: my $location;
11923: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11924:
11925: if ($file =~ m-^/adm/-) {
11926: $file=~s-^/adm/wrapper/-/-;
11927: $file=~s-^/adm/coursedocs/showdoc/-/-;
11928: }
1.882 albertel 11929:
1.1139 www 11930: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11931: $location = $file;
1.609 banghart 11932: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11933: my ($udom,$uname,$filename)=
1.811 albertel 11934: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11935: my $home=&homeserver($uname,$udom);
11936: my $is_me=0;
11937: my @ids=¤t_machine_ids();
11938: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11939: if ($is_me) {
1.1117 foxr 11940: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11941: } else {
11942: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11943: $udom.'/'.$uname.'/'.$filename;
11944: }
1.882 albertel 11945: } elsif ($file =~ m-^/adm/-) {
11946: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11947: } else {
11948: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11949: $file=~s:^/(res|priv)/:/:;
11950: my $space=$1;
1.590 banghart 11951: if ( !( $file =~ m:^/:) ) {
11952: $location = $dir. '/'.$file;
11953: } else {
1.1142 raeburn 11954: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11955: }
1.59 albertel 11956: }
1.590 banghart 11957: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11958: while ($location=~m{/\.\./}) {
11959: if ($location =~ m{/[^/]+/\.\./}) {
11960: $location=~ s{/[^/]+/\.\./}{/}g;
11961: } else {
11962: $location=~ s{/\.\./}{/}g;
11963: }
11964: } #remove dir/..
1.590 banghart 11965: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11966: return $location;
1.46 www 11967: }
1.36 albertel 11968:
1.46 www 11969: sub hreflocation {
11970: my ($dir,$file)=@_;
1.980 raeburn 11971: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11972: $file=filelocation($dir,$file);
1.700 albertel 11973: } elsif ($file=~m-^/adm/-) {
11974: $file=~s-^/adm/wrapper/-/-;
11975: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11976: }
11977: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11978: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11979: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11980: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11981: {/uploaded/$1/$2/}x;
1.46 www 11982: }
1.913 albertel 11983: if ($file=~ m{^/userfiles/}) {
11984: $file =~ s{^/userfiles/}{/uploaded/};
11985: }
1.462 albertel 11986: return $file;
1.465 albertel 11987: }
11988:
1.1139 www 11989:
11990:
11991:
11992:
1.465 albertel 11993: sub current_machine_domains {
1.853 albertel 11994: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11995: }
11996:
11997: sub machine_domains {
11998: my ($hostname) = @_;
1.465 albertel 11999: my @domains;
1.838 albertel 12000: my %hostname = &all_hostnames();
1.465 albertel 12001: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12002: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12003: if ($hostname eq $name) {
1.844 albertel 12004: push(@domains,&host_domain($id));
1.465 albertel 12005: }
12006: }
12007: return @domains;
12008: }
12009:
12010: sub current_machine_ids {
1.853 albertel 12011: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12012: }
12013:
12014: sub machine_ids {
12015: my ($hostname) = @_;
12016: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12017: my @ids;
1.888 albertel 12018: my %name_to_host = &all_names();
1.889 albertel 12019: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12020: return @{ $name_to_host{$hostname} };
12021: }
12022: return;
1.31 www 12023: }
12024:
1.824 raeburn 12025: sub additional_machine_domains {
12026: my @domains;
12027: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12028: while( my $line = <$fh>) {
12029: $line =~ s/\s//g;
12030: push(@domains,$line);
12031: }
12032: return @domains;
12033: }
12034:
12035: sub default_login_domain {
12036: my $domain = $perlvar{'lonDefDomain'};
12037: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12038: foreach my $posdom (¤t_machine_domains(),
12039: &additional_machine_domains()) {
12040: if (lc($posdom) eq lc($testdomain)) {
12041: $domain=$posdom;
12042: last;
12043: }
12044: }
12045: return $domain;
12046: }
12047:
1.31 www 12048: # ------------------------------------------------------------- Declutters URLs
12049:
12050: sub declutter {
12051: my $thisfn=shift;
1.569 albertel 12052: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 12053: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12054: $thisfn=~s{^/home/httpd/html}{};
12055: }
1.31 www 12056: $thisfn=~s/^\///;
1.697 albertel 12057: $thisfn=~s|^adm/wrapper/||;
12058: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12059: $thisfn=~s/^res\///;
1.1172 bisitz 12060: $thisfn=~s/^priv\///;
1.1032 raeburn 12061: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12062: $thisfn=~s/\?.+$//;
12063: }
1.268 www 12064: return $thisfn;
12065: }
12066:
12067: # ------------------------------------------------------------- Clutter up URLs
12068:
12069: sub clutter {
12070: my $thisfn='/'.&declutter(shift);
1.887 albertel 12071: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12072: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12073: $thisfn='/res'.$thisfn;
12074: }
1.1031 raeburn 12075: if ($thisfn !~m|^/adm|) {
12076: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12077: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12078: } else {
12079: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12080: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12081: if ($embstyle eq 'ssi'
12082: || ($embstyle eq 'hdn')
12083: || ($embstyle eq 'rat')
12084: || ($embstyle eq 'prv')
12085: || ($embstyle eq 'ign')) {
12086: #do nothing with these
12087: } elsif (($embstyle eq 'img')
1.695 albertel 12088: || ($embstyle eq 'emb')
12089: || ($embstyle eq 'wrp')) {
12090: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12091: } elsif ($embstyle eq 'unk'
12092: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12093: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12094: } else {
1.718 www 12095: # &logthis("Got a blank emb style");
1.695 albertel 12096: }
1.694 albertel 12097: }
12098: }
1.31 www 12099: return $thisfn;
1.12 www 12100: }
12101:
1.787 albertel 12102: sub clutter_with_no_wrapper {
12103: my $uri = &clutter(shift);
12104: if ($uri =~ m-^/adm/-) {
12105: $uri =~ s-^/adm/wrapper/-/-;
12106: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12107: }
12108: return $uri;
12109: }
12110:
1.557 albertel 12111: sub freeze_escape {
12112: my ($value)=@_;
12113: if (ref($value)) {
12114: $value=&nfreeze($value);
12115: return '__FROZEN__'.&escape($value);
12116: }
12117: return &escape($value);
12118: }
12119:
1.11 www 12120:
1.557 albertel 12121: sub thaw_unescape {
12122: my ($value)=@_;
12123: if ($value =~ /^__FROZEN__/) {
12124: substr($value,0,10,undef);
12125: $value=&unescape($value);
12126: return &thaw($value);
12127: }
12128: return &unescape($value);
12129: }
12130:
1.436 albertel 12131: sub correct_line_ends {
12132: my ($result)=@_;
12133: $$result =~s/\r\n/\n/mg;
12134: $$result =~s/\r/\n/mg;
1.415 albertel 12135: }
1.1 albertel 12136: # ================================================================ Main Program
12137:
1.184 www 12138: sub goodbye {
1.204 albertel 12139: &logthis("Starting Shut down");
1.443 albertel 12140: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12141: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12142: #converted
1.599 albertel 12143: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12144: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12145: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12146: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12147: #1.1 only
1.870 albertel 12148: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12149: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12150: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12151: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12152: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12153: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12154: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12155: &flushcourselogs();
12156: &logthis("Shutting down");
12157: }
12158:
1.852 albertel 12159: sub get_dns {
1.1172.2.17 raeburn 12160: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12161: if (!$ignore_cache) {
12162: my ($content,$cached)=
12163: &Apache::lonnet::is_cached_new('dns',$url);
12164: if ($cached) {
1.1172.2.17 raeburn 12165: &$func($content,$hashref);
1.869 albertel 12166: return;
12167: }
12168: }
12169:
12170: my %alldns;
1.852 albertel 12171: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12172: foreach my $dns (<$config>) {
12173: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12174: my $line = $1;
12175: my ($host,$protocol) = split(/:/,$line);
12176: if ($protocol ne 'https') {
12177: $protocol = 'http';
12178: }
12179: $alldns{$host} = $protocol;
1.869 albertel 12180: }
12181: while (%alldns) {
1.1172.2.52 raeburn 12182: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12183: my $ua=new LWP::UserAgent;
1.1134 raeburn 12184: $ua->timeout(30);
1.979 raeburn 12185: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12186: my $response=$ua->request($request);
1.979 raeburn 12187: delete($alldns{$dns});
1.852 albertel 12188: next if ($response->is_error());
12189: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 12190: unless ($nocache) {
1.1172.2.23 raeburn 12191: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 12192: }
12193: &$func(\@content,$hashref);
1.869 albertel 12194: return;
1.852 albertel 12195: }
12196: close($config);
1.871 albertel 12197: my $which = (split('/',$url))[3];
12198: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12199: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12200: my @content = <$config>;
1.1172.2.17 raeburn 12201: &$func(\@content,$hashref);
12202: return;
12203: }
12204:
12205: # ------------------------------------------------------Get DNS checksums file
12206: sub parse_dns_checksums_tab {
12207: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 12208: my $lonhost = $perlvar{'lonHostID'};
12209: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 12210: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 12211: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12212: my $webconfdir = '/etc/httpd/conf';
12213: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12214: $webconfdir = '/etc/apache2';
12215: } elsif ($distro =~ /^sles(\d+)$/) {
12216: if ($1 >= 10) {
12217: $webconfdir = '/etc/apache2';
12218: }
12219: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12220: if ($1 >= 10.0) {
12221: $webconfdir = '/etc/apache2';
12222: }
12223: }
1.1172.2.17 raeburn 12224: my ($release,$timestamp) = split(/\-/,$loncaparev);
12225: my (%chksum,%revnum);
12226: if (ref($lines) eq 'ARRAY') {
12227: chomp(@{$lines});
1.1172.2.34 raeburn 12228: my $version = shift(@{$lines});
12229: if ($version eq $release) {
1.1172.2.17 raeburn 12230: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 12231: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 12232: if ($file =~ m{^/etc/httpd/conf}) {
12233: if ($webconfdir eq '/etc/apache2') {
12234: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12235: }
12236: }
1.1172.2.34 raeburn 12237: $chksum{$file} = $shasum;
12238: $revnum{$file} = $version;
1.1172.2.17 raeburn 12239: }
12240: if (ref($hashref) eq 'HASH') {
12241: %{$hashref} = (
12242: sums => \%chksum,
12243: versions => \%revnum,
12244: );
12245: }
12246: }
12247: }
1.869 albertel 12248: return;
1.852 albertel 12249: }
1.1172.2.17 raeburn 12250:
12251: sub fetch_dns_checksums {
12252: my %checksums;
1.1172.2.34 raeburn 12253: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 12254: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 12255: my ($release,$timestamp) = split(/\-/,$loncaparev);
12256: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 12257: \%checksums);
12258: return \%checksums;
12259: }
12260:
1.327 albertel 12261: # ------------------------------------------------------------ Read domain file
12262: {
1.852 albertel 12263: my $loaded;
1.846 albertel 12264: my %domain;
12265:
1.852 albertel 12266: sub parse_domain_tab {
12267: my ($lines) = @_;
12268: foreach my $line (@$lines) {
12269: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12270:
1.846 albertel 12271: chomp($line);
1.852 albertel 12272: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12273: my %this_domain;
12274: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12275: 'lang_def', 'city', 'longi', 'lati',
12276: 'primary') {
12277: $this_domain{$field} = shift(@elements);
12278: }
12279: $domain{$name} = \%this_domain;
1.852 albertel 12280: }
12281: }
1.864 albertel 12282:
12283: sub reset_domain_info {
12284: undef($loaded);
12285: undef(%domain);
12286: }
12287:
1.852 albertel 12288: sub load_domain_tab {
1.1172.2.70 raeburn 12289: my ($ignore_cache,$nocache) = @_;
12290: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 12291: my $fh;
12292: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12293: my @lines = <$fh>;
12294: &parse_domain_tab(\@lines);
1.448 albertel 12295: }
1.852 albertel 12296: close($fh);
12297: $loaded = 1;
1.327 albertel 12298: }
1.846 albertel 12299:
12300: sub domain {
1.852 albertel 12301: &load_domain_tab() if (!$loaded);
12302:
1.846 albertel 12303: my ($name,$what) = @_;
12304: return if ( !exists($domain{$name}) );
12305:
12306: if (!$what) {
12307: return $domain{$name}{'description'};
12308: }
12309: return $domain{$name}{$what};
12310: }
1.974 raeburn 12311:
12312: sub domain_info {
12313: &load_domain_tab() if (!$loaded);
12314: return %domain;
12315: }
12316:
1.327 albertel 12317: }
12318:
12319:
1.1 albertel 12320: # ------------------------------------------------------------- Read hosts file
12321: {
1.838 albertel 12322: my %hostname;
1.844 albertel 12323: my %hostdom;
1.845 albertel 12324: my %libserv;
1.852 albertel 12325: my $loaded;
1.888 albertel 12326: my %name_to_host;
1.1074 raeburn 12327: my %internetdom;
1.1107 raeburn 12328: my %LC_dns_serv;
1.852 albertel 12329:
12330: sub parse_hosts_tab {
12331: my ($file) = @_;
12332: foreach my $configline (@$file) {
12333: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12334: chomp($configline);
12335: if ($configline =~ /^\^/) {
12336: if ($configline =~ /^\^([\w.\-]+)/) {
12337: $LC_dns_serv{$1} = 1;
12338: }
12339: next;
12340: }
1.1074 raeburn 12341: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12342: $name=~s/\s//g;
12343: if ($id && $domain && $role && $name) {
12344: $hostname{$id}=$name;
1.888 albertel 12345: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12346: $hostdom{$id}=$domain;
12347: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12348: if (defined($protocol)) {
12349: if ($protocol eq 'https') {
12350: $protocol{$id} = $protocol;
12351: } else {
12352: $protocol{$id} = 'http';
12353: }
1.968 raeburn 12354: } else {
1.969 raeburn 12355: $protocol{$id} = 'http';
1.968 raeburn 12356: }
1.1074 raeburn 12357: if (defined($intdom)) {
12358: $internetdom{$id} = $intdom;
12359: }
1.852 albertel 12360: }
12361: }
12362: }
1.864 albertel 12363:
12364: sub reset_hosts_info {
1.897 albertel 12365: &purge_remembered();
1.864 albertel 12366: &reset_domain_info();
12367: &reset_hosts_ip_info();
1.892 albertel 12368: undef(%name_to_host);
1.864 albertel 12369: undef(%hostname);
12370: undef(%hostdom);
12371: undef(%libserv);
12372: undef($loaded);
12373: }
1.1 albertel 12374:
1.852 albertel 12375: sub load_hosts_tab {
1.1172.2.70 raeburn 12376: my ($ignore_cache,$nocache) = @_;
12377: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852 albertel 12378: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12379: my @config = <$config>;
12380: &parse_hosts_tab(\@config);
12381: close($config);
12382: $loaded=1;
1.1 albertel 12383: }
1.852 albertel 12384:
1.838 albertel 12385: sub hostname {
1.852 albertel 12386: &load_hosts_tab() if (!$loaded);
12387:
1.838 albertel 12388: my ($lonid) = @_;
12389: return $hostname{$lonid};
12390: }
1.845 albertel 12391:
1.838 albertel 12392: sub all_hostnames {
1.852 albertel 12393: &load_hosts_tab() if (!$loaded);
12394:
1.838 albertel 12395: return %hostname;
12396: }
1.845 albertel 12397:
1.888 albertel 12398: sub all_names {
1.1172.2.70 raeburn 12399: my ($ignore_cache,$nocache) = @_;
12400: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 12401:
12402: return %name_to_host;
12403: }
12404:
1.974 raeburn 12405: sub all_host_domain {
12406: &load_hosts_tab() if (!$loaded);
12407: return %hostdom;
12408: }
12409:
1.845 albertel 12410: sub is_library {
1.852 albertel 12411: &load_hosts_tab() if (!$loaded);
12412:
1.845 albertel 12413: return exists($libserv{$_[0]});
12414: }
12415:
12416: sub all_library {
1.852 albertel 12417: &load_hosts_tab() if (!$loaded);
12418:
1.845 albertel 12419: return %libserv;
12420: }
12421:
1.1062 droeschl 12422: sub unique_library {
12423: #2x reverse removes all hostnames that appear more than once
12424: my %unique = reverse &all_library();
12425: return reverse %unique;
12426: }
12427:
1.841 albertel 12428: sub get_servers {
1.852 albertel 12429: &load_hosts_tab() if (!$loaded);
12430:
1.841 albertel 12431: my ($domain,$type) = @_;
12432: my %possible_hosts = ($type eq 'library') ? %libserv
12433: : %hostname;
12434: my %result;
1.842 albertel 12435: if (ref($domain) eq 'ARRAY') {
12436: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12437: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12438: $result{$host} = $hostname;
12439: }
12440: }
12441: } else {
12442: while ( my ($host,$hostname) = each(%possible_hosts)) {
12443: if ($hostdom{$host} eq $domain) {
12444: $result{$host} = $hostname;
12445: }
1.841 albertel 12446: }
12447: }
12448: return %result;
12449: }
1.845 albertel 12450:
1.1062 droeschl 12451: sub get_unique_servers {
12452: my %unique = reverse &get_servers(@_);
12453: return reverse %unique;
12454: }
12455:
1.844 albertel 12456: sub host_domain {
1.852 albertel 12457: &load_hosts_tab() if (!$loaded);
12458:
1.844 albertel 12459: my ($lonid) = @_;
12460: return $hostdom{$lonid};
12461: }
12462:
1.841 albertel 12463: sub all_domains {
1.852 albertel 12464: &load_hosts_tab() if (!$loaded);
12465:
1.841 albertel 12466: my %seen;
12467: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12468: return @uniq;
12469: }
1.1074 raeburn 12470:
12471: sub internet_dom {
12472: &load_hosts_tab() if (!$loaded);
12473:
12474: my ($lonid) = @_;
12475: return $internetdom{$lonid};
12476: }
1.1107 raeburn 12477:
12478: sub is_LC_dns {
12479: &load_hosts_tab() if (!$loaded);
12480:
12481: my ($hostname) = @_;
12482: return exists($LC_dns_serv{$hostname});
12483: }
12484:
1.1 albertel 12485: }
12486:
1.847 albertel 12487: {
12488: my %iphost;
1.856 albertel 12489: my %name_to_ip;
12490: my %lonid_to_ip;
1.869 albertel 12491:
1.847 albertel 12492: sub get_hosts_from_ip {
12493: my ($ip) = @_;
12494: my %iphosts = &get_iphost();
12495: if (ref($iphosts{$ip})) {
12496: return @{$iphosts{$ip}};
12497: }
12498: return;
1.839 albertel 12499: }
1.864 albertel 12500:
12501: sub reset_hosts_ip_info {
12502: undef(%iphost);
12503: undef(%name_to_ip);
12504: undef(%lonid_to_ip);
12505: }
1.856 albertel 12506:
12507: sub get_host_ip {
12508: my ($lonid) = @_;
12509: if (exists($lonid_to_ip{$lonid})) {
12510: return $lonid_to_ip{$lonid};
12511: }
12512: my $name=&hostname($lonid);
12513: my $ip = gethostbyname($name);
12514: return if (!$ip || length($ip) ne 4);
12515: $ip=inet_ntoa($ip);
12516: $name_to_ip{$name} = $ip;
12517: $lonid_to_ip{$lonid} = $ip;
12518: return $ip;
12519: }
1.847 albertel 12520:
12521: sub get_iphost {
1.1172.2.70 raeburn 12522: my ($ignore_cache,$nocache) = @_;
1.894 albertel 12523:
1.869 albertel 12524: if (!$ignore_cache) {
12525: if (%iphost) {
12526: return %iphost;
12527: }
12528: my ($ip_info,$cached)=
12529: &Apache::lonnet::is_cached_new('iphost','iphost');
12530: if ($cached) {
12531: %iphost = %{$ip_info->[0]};
12532: %name_to_ip = %{$ip_info->[1]};
12533: %lonid_to_ip = %{$ip_info->[2]};
12534: return %iphost;
12535: }
12536: }
1.894 albertel 12537:
12538: # get yesterday's info for fallback
12539: my %old_name_to_ip;
12540: my ($ip_info,$cached)=
12541: &Apache::lonnet::is_cached_new('iphost','iphost');
12542: if ($cached) {
12543: %old_name_to_ip = %{$ip_info->[1]};
12544: }
12545:
1.1172.2.70 raeburn 12546: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 12547: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12548: my $ip;
12549: if (!exists($name_to_ip{$name})) {
12550: $ip = gethostbyname($name);
12551: if (!$ip || length($ip) ne 4) {
1.894 albertel 12552: if (defined($old_name_to_ip{$name})) {
12553: $ip = $old_name_to_ip{$name};
12554: &logthis("Can't find $name defaulting to old $ip");
12555: } else {
12556: &logthis("Name $name no IP found");
12557: next;
12558: }
12559: } else {
12560: $ip=inet_ntoa($ip);
1.847 albertel 12561: }
12562: $name_to_ip{$name} = $ip;
12563: } else {
12564: $ip = $name_to_ip{$name};
1.653 albertel 12565: }
1.888 albertel 12566: foreach my $id (@{ $name_to_host{$name} }) {
12567: $lonid_to_ip{$id} = $ip;
12568: }
12569: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12570: }
1.1172.2.70 raeburn 12571: unless ($nocache) {
12572: &do_cache_new('iphost','iphost',
12573: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12574: 48*60*60);
12575: }
1.869 albertel 12576:
1.847 albertel 12577: return %iphost;
1.598 albertel 12578: }
12579:
1.992 raeburn 12580: #
12581: # Given a DNS returns the loncapa host name for that DNS
12582: #
12583: sub host_from_dns {
12584: my ($dns) = @_;
12585: my @hosts;
12586: my $ip;
12587:
1.993 raeburn 12588: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12589: $ip = $name_to_ip{$dns};
12590: }
12591: if (!$ip) {
12592: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12593: if (length($ip) == 4) {
12594: $ip = &IO::Socket::inet_ntoa($ip);
12595: }
12596: }
12597: if ($ip) {
12598: @hosts = get_hosts_from_ip($ip);
12599: return $hosts[0];
12600: }
12601: return undef;
1.986 foxr 12602: }
1.992 raeburn 12603:
1.1074 raeburn 12604: sub get_internet_names {
12605: my ($lonid) = @_;
12606: return if ($lonid eq '');
12607: my ($idnref,$cached)=
12608: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12609: if ($cached) {
12610: return $idnref;
12611: }
12612: my $ip = &get_host_ip($lonid);
12613: my @hosts = &get_hosts_from_ip($ip);
12614: my %iphost = &get_iphost();
12615: my (@idns,%seen);
12616: foreach my $id (@hosts) {
12617: my $dom = &host_domain($id);
12618: my $prim_id = &domain($dom,'primary');
12619: my $prim_ip = &get_host_ip($prim_id);
12620: next if ($seen{$prim_ip});
12621: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12622: foreach my $id (@{$iphost{$prim_ip}}) {
12623: my $intdom = &internet_dom($id);
12624: unless (grep(/^\Q$intdom\E$/,@idns)) {
12625: push(@idns,$intdom);
12626: }
12627: }
12628: }
12629: $seen{$prim_ip} = 1;
12630: }
1.1172.2.23 raeburn 12631: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12632: }
12633:
1.986 foxr 12634: }
12635:
1.1079 raeburn 12636: sub all_loncaparevs {
1.1172.2.39 raeburn 12637: 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 12638: }
12639:
1.1172.2.27 raeburn 12640: # ------------------------------------------------------- Read loncaparev table
12641: {
12642: sub load_loncaparevs {
12643: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12644: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12645: while (my $configline=<$config>) {
12646: chomp($configline);
12647: my ($hostid,$loncaparev)=split(/:/,$configline);
12648: $loncaparevs{$hostid}=$loncaparev;
12649: }
12650: close($config);
12651: }
12652: }
12653: }
12654: }
12655:
12656: # ----------------------------------------------------- Read serverhostID table
12657: {
12658: sub load_serverhomeIDs {
12659: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12660: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12661: while (my $configline=<$config>) {
12662: chomp($configline);
12663: my ($name,$id)=split(/:/,$configline);
12664: $serverhomeIDs{$name}=$id;
12665: }
12666: close($config);
12667: }
12668: }
12669: }
12670: }
12671:
12672:
1.862 albertel 12673: BEGIN {
12674:
12675: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12676: unless ($readit) {
12677: {
12678: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12679: %perlvar = (%perlvar,%{$configvars});
12680: }
12681:
12682:
1.1 albertel 12683: # ------------------------------------------------------ Read spare server file
12684: {
1.448 albertel 12685: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12686:
12687: while (my $configline=<$config>) {
12688: chomp($configline);
1.284 matthew 12689: if ($configline) {
1.784 albertel 12690: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12691: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12692: push(@{ $spareid{$type} }, $host);
1.1 albertel 12693: }
12694: }
1.448 albertel 12695: close($config);
1.1 albertel 12696: }
1.11 www 12697: # ------------------------------------------------------------ Read permissions
12698: {
1.448 albertel 12699: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12700:
12701: while (my $configline=<$config>) {
1.448 albertel 12702: chomp($configline);
12703: if ($configline) {
12704: my ($role,$perm)=split(/ /,$configline);
12705: if ($perm ne '') { $pr{$role}=$perm; }
12706: }
1.11 www 12707: }
1.448 albertel 12708: close($config);
1.11 www 12709: }
12710:
12711: # -------------------------------------------- Read plain texts for permissions
12712: {
1.448 albertel 12713: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12714:
12715: while (my $configline=<$config>) {
1.448 albertel 12716: chomp($configline);
12717: if ($configline) {
1.742 raeburn 12718: my ($short,@plain)=split(/:/,$configline);
12719: %{$prp{$short}} = ();
12720: if (@plain > 0) {
12721: $prp{$short}{'std'} = $plain[0];
12722: for (my $i=1; $i<@plain; $i++) {
12723: $prp{$short}{'alt'.$i} = $plain[$i];
12724: }
12725: }
1.448 albertel 12726: }
1.135 www 12727: }
1.448 albertel 12728: close($config);
1.135 www 12729: }
12730:
12731: # ---------------------------------------------------------- Read package table
12732: {
1.448 albertel 12733: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12734:
12735: while (my $configline=<$config>) {
1.483 albertel 12736: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12737: chomp($configline);
12738: my ($short,$plain)=split(/:/,$configline);
12739: my ($pack,$name)=split(/\&/,$short);
12740: if ($plain ne '') {
12741: $packagetab{$pack.'&'.$name.'&name'}=$name;
12742: $packagetab{$short}=$plain;
12743: }
1.11 www 12744: }
1.448 albertel 12745: close($config);
1.329 matthew 12746: }
12747:
1.1172.2.27 raeburn 12748: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 12749:
1.1172.2.27 raeburn 12750: &load_loncaparevs();
12751:
12752: # ------------------------------------------------------- Read serverhostID table
12753:
12754: &load_serverhomeIDs();
1.1074 raeburn 12755:
1.1172.2.27 raeburn 12756: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12757: {
12758: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12759: if (-e $file) {
12760: my $parser = HTML::LCParser->new($file);
12761: while (my $token = $parser->get_token()) {
12762: if ($token->[0] eq 'S') {
12763: my $item = $token->[1];
12764: my $name = $token->[2]{'name'};
12765: my $value = $token->[2]{'value'};
12766: if ($item ne '' && $name ne '' && $value ne '') {
12767: my $release = $parser->get_text();
12768: $release =~ s/(^\s*|\s*$ )//gx;
12769: $needsrelease{$item.':'.$name.':'.$value} = $release;
12770: }
12771: }
12772: }
12773: }
1.1073 raeburn 12774: }
12775:
1.1138 raeburn 12776: # ---------------------------------------------------------- Read managers table
12777: {
12778: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12779: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12780: while (my $configline=<$config>) {
12781: chomp($configline);
12782: next if ($configline =~ /^\#/);
12783: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12784: $managerstab{$configline} = 1;
12785: }
12786: }
12787: close($config);
12788: }
12789: }
12790: }
12791:
1.329 matthew 12792: # ------------- set up temporary directory
12793: {
1.1117 foxr 12794: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12795:
1.11 www 12796: }
12797:
1.794 albertel 12798: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12799: 'compress_threshold'=> 20_000,
12800: });
1.185 www 12801:
1.281 www 12802: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12803: $dumpcount=0;
1.958 www 12804: $locknum=0;
1.22 www 12805:
1.163 harris41 12806: &logtouch();
1.672 albertel 12807: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12808: $readit=1;
1.564 albertel 12809: {
12810: use integer;
12811: my $test=(2**32)+1;
1.568 albertel 12812: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12813: &logthis(" Detected 64bit platform ($_64bit)");
12814: }
1.195 www 12815: }
1.1 albertel 12816: }
1.179 www 12817:
1.1 albertel 12818: 1;
1.191 harris41 12819: __END__
12820:
1.243 albertel 12821: =pod
12822:
1.191 harris41 12823: =head1 NAME
12824:
1.243 albertel 12825: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12826:
12827: =head1 SYNOPSIS
12828:
1.243 albertel 12829: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12830:
12831: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12832:
1.243 albertel 12833: Common parameters:
12834:
12835: =over 4
12836:
12837: =item *
12838:
12839: $uname : an internal username (if $cname expecting a course Id specifically)
12840:
12841: =item *
12842:
12843: $udom : a domain (if $cdom expecting a course's domain specifically)
12844:
12845: =item *
12846:
12847: $symb : a resource instance identifier
12848:
12849: =item *
12850:
12851: $namespace : the name of a .db file that contains the data needed or
12852: being set.
12853:
12854: =back
12855:
1.394 bowersj2 12856: =head1 OVERVIEW
1.191 harris41 12857:
1.394 bowersj2 12858: lonnet provides subroutines which interact with the
12859: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12860: about classes, users, and resources.
1.243 albertel 12861:
12862: For many of these objects you can also use this to store data about
12863: them or modify them in various ways.
1.191 harris41 12864:
1.394 bowersj2 12865: =head2 Symbs
1.191 harris41 12866:
1.394 bowersj2 12867: To identify a specific instance of a resource, LON-CAPA uses symbols
12868: or "symbs"X<symb>. These identifiers are built from the URL of the
12869: map, the resource number of the resource in the map, and the URL of
12870: the resource itself. The latter is somewhat redundant, but might help
12871: if maps change.
12872:
12873: An example is
12874:
12875: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12876:
12877: The respective map entry is
12878:
12879: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12880: title="Problem 2">
12881: </resource>
12882:
12883: Symbs are used by the random number generator, as well as to store and
12884: restore data specific to a certain instance of for example a problem.
12885:
12886: =head2 Storing And Retrieving Data
12887:
12888: X<store()>X<cstore()>X<restore()>Three of the most important functions
12889: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12890: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12891: is is the non-critical message twin of cstore. These functions are for
12892: handlers to store a perl hash to a user's permanent data space in an
12893: easy manner, and to retrieve it again on another call. It is expected
12894: that a handler would use this once at the beginning to retrieve data,
12895: and then again once at the end to send only the new data back.
12896:
12897: The data is stored in the user's data directory on the user's
12898: homeserver under the ID of the course.
12899:
12900: The hash that is returned by restore will have all of the previous
12901: value for all of the elements of the hash.
12902:
12903: Example:
12904:
12905: #creating a hash
12906: my %hash;
12907: $hash{'foo'}='bar';
12908:
12909: #storing it
12910: &Apache::lonnet::cstore(\%hash);
12911:
12912: #changing a value
12913: $hash{'foo'}='notbar';
12914:
12915: #adding a new value
12916: $hash{'bar'}='foo';
12917: &Apache::lonnet::cstore(\%hash);
12918:
12919: #retrieving the hash
12920: my %history=&Apache::lonnet::restore();
12921:
12922: #print the hash
12923: foreach my $key (sort(keys(%history))) {
12924: print("\%history{$key} = $history{$key}");
12925: }
12926:
12927: Will print out:
1.191 harris41 12928:
1.394 bowersj2 12929: %history{1:foo} = bar
12930: %history{1:keys} = foo:timestamp
12931: %history{1:timestamp} = 990455579
12932: %history{2:bar} = foo
12933: %history{2:foo} = notbar
12934: %history{2:keys} = foo:bar:timestamp
12935: %history{2:timestamp} = 990455580
12936: %history{bar} = foo
12937: %history{foo} = notbar
12938: %history{timestamp} = 990455580
12939: %history{version} = 2
12940:
12941: Note that the special hash entries C<keys>, C<version> and
12942: C<timestamp> were added to the hash. C<version> will be equal to the
12943: total number of versions of the data that have been stored. The
12944: C<timestamp> attribute will be the UNIX time the hash was
12945: stored. C<keys> is available in every historical section to list which
12946: keys were added or changed at a specific historical revision of a
12947: hash.
12948:
12949: B<Warning>: do not store the hash that restore returns directly. This
12950: will cause a mess since it will restore the historical keys as if the
12951: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12952:
1.394 bowersj2 12953: Calling convention:
1.191 harris41 12954:
1.1172.2.27 raeburn 12955: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 12956: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 12957:
1.394 bowersj2 12958: For more detailed information, see lonnet specific documentation.
1.191 harris41 12959:
1.394 bowersj2 12960: =head1 RETURN MESSAGES
1.191 harris41 12961:
1.394 bowersj2 12962: =over 4
1.191 harris41 12963:
1.394 bowersj2 12964: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12965:
1.394 bowersj2 12966: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12967: when the connection is brought back up
1.191 harris41 12968:
1.394 bowersj2 12969: =item * B<con_failed>: unable to contact remote host and unable to save message
12970: for later delivery
1.191 harris41 12971:
1.967 bisitz 12972: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12973:
1.394 bowersj2 12974: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12975: that was requested
1.191 harris41 12976:
1.243 albertel 12977: =back
1.191 harris41 12978:
1.243 albertel 12979: =head1 PUBLIC SUBROUTINES
1.191 harris41 12980:
1.243 albertel 12981: =head2 Session Environment Functions
1.191 harris41 12982:
1.243 albertel 12983: =over 4
1.191 harris41 12984:
1.394 bowersj2 12985: =item *
12986: X<appenv()>
1.949 raeburn 12987: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12988: the user envirnoment file, and will be restored for each access this
1.620 albertel 12989: user makes during this session, also modifies the %env for the current
1.949 raeburn 12990: process. Optional rolesarrayref - if defined contains a reference to an array
12991: of roles which are exempt from the restriction on modifying user.role entries
12992: in the user's environment.db and in %env.
1.191 harris41 12993:
12994: =item *
1.394 bowersj2 12995: X<delenv()>
1.987 raeburn 12996: B<delenv($delthis,$regexp)>: removes all items from the session
12997: environment file that begin with $delthis. If the
12998: optional second arg - $regexp - is true, $delthis is treated as a
12999: regular expression, otherwise \Q$delthis\E is used.
13000: The values are also deleted from the current processes %env.
1.191 harris41 13001:
1.795 albertel 13002: =item * get_env_multiple($name)
13003:
13004: gets $name from the %env hash, it seemlessly handles the cases where multiple
13005: values may be defined and end up as an array ref.
13006:
13007: returns an array of values
13008:
1.243 albertel 13009: =back
13010:
13011: =head2 User Information
1.191 harris41 13012:
1.243 albertel 13013: =over 4
1.191 harris41 13014:
13015: =item *
1.394 bowersj2 13016: X<queryauthenticate()>
13017: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13018: authentication scheme
13019:
13020: =item *
1.394 bowersj2 13021: X<authenticate()>
1.1073 raeburn 13022: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13023: authenticate user from domain's lib servers (first use the current
13024: one). C<$upass> should be the users password.
1.1073 raeburn 13025: $checkdefauth is optional (value is 1 if a check should be made to
13026: authenticate user using default authentication method, and allow
13027: account creation if username does not have account in the domain).
13028: $clientcancheckhost is optional (value is 1 if checking whether the
13029: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13030:
13031: =item *
1.394 bowersj2 13032: X<homeserver()>
13033: B<homeserver($uname,$udom)>: find the server which has
13034: the user's directory and files (there must be only one), this caches
13035: the answer, and also caches if there is a borken connection.
1.191 harris41 13036:
13037: =item *
1.394 bowersj2 13038: X<idget()>
13039: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13040: (IDs are a unique resource in a domain, there must be only 1 ID per
13041: username, and only 1 username per ID in a specific domain) (returns
13042: hash: id=>name,id=>name)
1.191 harris41 13043:
13044: =item *
1.394 bowersj2 13045: X<idrget()>
13046: B<idrget($udom,@unames)>: find the IDs behind a list of
13047: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13048:
13049: =item *
1.394 bowersj2 13050: X<idput()>
13051: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 13052:
13053: =item *
1.394 bowersj2 13054: X<rolesinit()>
1.1169 droeschl 13055: B<rolesinit($udom,$username)>: get user privileges.
13056: returns user role, first access and timer interval hashes
1.243 albertel 13057:
13058: =item *
1.1171 droeschl 13059: X<privileged()>
13060: B<privileged($username,$domain)>: returns a true if user has a
13061: privileged and active role (i.e. su or dc), false otherwise.
13062:
13063: =item *
1.551 albertel 13064: X<getsection()>
13065: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13066: course $cname, return section name/number or '' for "not in course"
13067: and '-1' for "no section"
13068:
13069: =item *
1.394 bowersj2 13070: X<userenvironment()>
13071: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13072: passed in @what from the requested user's environment, returns a hash
13073:
1.858 raeburn 13074: =item *
13075: X<userlog_query()>
1.859 albertel 13076: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13077: activity.log file. %filters defines filters applied when parsing the
13078: log file. These can be start or end timestamps, or the type of action
13079: - log to look for Login or Logout events, check for Checkin or
13080: Checkout, role for role selection. The response is in the form
13081: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13082: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13083:
1.243 albertel 13084: =back
13085:
13086: =head2 User Roles
13087:
13088: =over 4
13089:
13090: =item *
13091:
1.1172.2.65 raeburn 13092: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13093: returns codes for allowed actions.
13094:
13095: The first argument is required, all others are optional.
13096:
13097: $priv is the privilege being checked.
13098: $uri contains additional information about what is being checked for access (e.g.,
13099: URL, course ID etc.).
13100: $symb is the unique resource instance identifier in a course; if needed,
13101: but not provided, it will be retrieved via a call to &symbread().
13102: $role is the role for which a priv is being checked (only used if priv is evb).
13103: $clientip is the user's IP address (only used when checking for access to portfolio
13104: files).
13105: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13106: prevents recursive calls to &allowed.
13107:
1.243 albertel 13108: F: full access
13109: U,I,K: authentication modes (cxx only)
13110: '': forbidden
13111: 1: user needs to choose course
13112: 2: browse allowed
1.766 albertel 13113: A: passphrase authentication needed
1.1172.2.65 raeburn 13114: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13115:
13116: =item *
13117:
1.1172.2.13 raeburn 13118: constructaccess($url,$setpriv) : check for access to construction space URL
13119:
13120: See if the owner domain and name in the URL match those in the
13121: expected environment. If so, return three element list
13122: ($ownername,$ownerdomain,$ownerhome).
13123:
13124: Otherwise return the null string.
13125:
13126: If second argument 'setpriv' is true, it assigns the privileges,
13127: and returns the same three element list, unless the owner has
13128: blocked "ad hoc" Domain Coordinator access to the Author Space,
13129: in which case the null string is returned.
13130:
13131: =item *
13132:
1.243 albertel 13133: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
13134: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
13135: and course level
13136:
13137: =item *
13138:
1.988 raeburn 13139: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13140: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13141: $type is Course (default) or Community.
1.988 raeburn 13142: If $forcedefault evaluates to true, text returned will be default
13143: text for $type. Otherwise, if this is a course, the text returned
13144: will be a custom name for the role (if defined in the course's
13145: environment). If no custom name is defined the default is returned.
13146:
1.832 raeburn 13147: =item *
13148:
1.1172.2.23 raeburn 13149: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13150: All arguments are optional. Returns a hash of a roles, either for
13151: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13152: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13153: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13154: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13155: For each key, value is set to colon-separated start and end times for
13156: the role. If no username and domain are specified, will default to
1.934 raeburn 13157: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13158: of role statuses (active, future or previous), roles
13159: (e.g., cc,in, st etc.) and domains of the roles which can be used
13160: to restrict the list of roles reported. If no array ref is
13161: provided for types, will default to return only active roles.
1.834 albertel 13162:
1.1172.2.13 raeburn 13163: =item *
13164:
13165: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
13166: user: $uname:$udom has a role in the course: $cdom_$cnum.
13167:
13168: Additional optional arguments are: $type (if role checking is to be restricted
13169: to certain user status types -- previous (expired roles), active (currently
13170: available roles) or future (roles available in the future), and
13171: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 13172: have active Domain Coordinator role in course's domain or in additional
13173: domains (specified in 'Domains to check for privileged users' in course
13174: environment -- set via: Course Settings -> Classlists and staff listing).
13175:
13176: =item *
13177:
13178: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13179: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13180: $possdomains and $possroles are optional array refs -- to domains to check and
13181: roles to check. If $possdomains is not specified, a dump will be done of the
13182: users' roles.db to check for a dc or su role in any domain. This can be
13183: time consuming if &privileged is called repeatedly (e.g., when displaying a
13184: classlist), so in such cases, supplying a $possdomains array is preferred, as
13185: this then allows &privileged_by_domain() to be used, which caches the identity
13186: of privileged users, eliminating the need for repeated calls to &dump().
13187:
13188: =item *
13189:
13190: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13191: where the outer hash keys are domains specified in the $possdomains array ref,
13192: next inner hash keys are privileged roles specified in the $roles array ref,
13193: and the innermost hash contains key = value pairs for username:domain = end:start
13194: for active or future "privileged" users with that role in that domain. To avoid
13195: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13196: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 13197:
1.243 albertel 13198: =back
13199:
13200: =head2 User Modification
13201:
13202: =over 4
13203:
13204: =item *
13205:
1.957 raeburn 13206: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13207: user for the level given by URL. Optional start and end dates (leave empty
13208: string or zero for "no date")
1.191 harris41 13209:
13210: =item *
13211:
1.243 albertel 13212: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13213: change a users, password, possible return values are: ok,
13214: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13215: refused
1.191 harris41 13216:
13217: =item *
13218:
1.243 albertel 13219: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13220:
13221: =item *
13222:
1.1058 raeburn 13223: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13224: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13225:
13226: will update user information (firstname,middlename,lastname,generation,
13227: permanentemail), and if forceid is true, student/employee ID also.
13228: A user's institutional affiliation(s) can also be updated.
13229: User information fields will not be overwritten with empty entries
13230: unless the field is included in the $candelete array reference.
13231: This array is included when a single user is modified via "Manage Users",
13232: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13233:
13234: =item *
13235:
1.286 matthew 13236: modifystudent
13237:
1.957 raeburn 13238: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 13239: The course id is resolved based on the current user's environment.
13240: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13241: associated with a course.
13242:
1.297 matthew 13243: This call is essentially a wrapper for lonnet::modifyuser and
13244: lonnet::modify_student_enrollment
1.286 matthew 13245:
13246: Inputs:
13247:
13248: =over 4
13249:
1.957 raeburn 13250: =item B<$udom> Student's loncapa domain
1.286 matthew 13251:
1.957 raeburn 13252: =item B<$uname> Student's loncapa login name
1.286 matthew 13253:
1.964 bisitz 13254: =item B<$uid> Student/Employee ID
1.286 matthew 13255:
1.957 raeburn 13256: =item B<$umode> Student's authentication mode
1.286 matthew 13257:
1.957 raeburn 13258: =item B<$upass> Student's password
1.286 matthew 13259:
1.957 raeburn 13260: =item B<$first> Student's first name
1.286 matthew 13261:
1.957 raeburn 13262: =item B<$middle> Student's middle name
1.286 matthew 13263:
1.957 raeburn 13264: =item B<$last> Student's last name
1.286 matthew 13265:
1.957 raeburn 13266: =item B<$gene> Student's generation
1.286 matthew 13267:
1.957 raeburn 13268: =item B<$usec> Student's section in course
1.286 matthew 13269:
13270: =item B<$end> Unix time of the roles expiration
13271:
13272: =item B<$start> Unix time of the roles start date
13273:
13274: =item B<$forceid> If defined, allow $uid to be changed
13275:
13276: =item B<$desiredhome> server to use as home server for student
13277:
1.957 raeburn 13278: =item B<$email> Student's permanent e-mail address
13279:
13280: =item B<$type> Type of enrollment (auto or manual)
13281:
1.963 raeburn 13282: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13283:
13284: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13285:
1.963 raeburn 13286: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13287:
1.963 raeburn 13288: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13289:
1.1172.2.19 raeburn 13290: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13291:
13292: =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 13293:
1.286 matthew 13294: =back
1.297 matthew 13295:
13296: =item *
13297:
13298: modify_student_enrollment
13299:
1.1172.2.31 raeburn 13300: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13301: 'role.request.course' must be defined for this function to proceed.
13302:
13303: Inputs:
13304:
13305: =over 4
13306:
1.1172.2.31 raeburn 13307: =item $udom, student's domain
1.297 matthew 13308:
1.1172.2.31 raeburn 13309: =item $uname, student's name
1.297 matthew 13310:
1.1172.2.31 raeburn 13311: =item $uid, student's user id
1.297 matthew 13312:
1.1172.2.31 raeburn 13313: =item $first, student's first name
1.297 matthew 13314:
13315: =item $middle
13316:
13317: =item $last
13318:
13319: =item $gene
13320:
13321: =item $usec
13322:
13323: =item $end
13324:
13325: =item $start
13326:
1.957 raeburn 13327: =item $type
13328:
13329: =item $locktype
13330:
13331: =item $cid
13332:
13333: =item $selfenroll
13334:
13335: =item $context
13336:
1.1172.2.19 raeburn 13337: =item $credits, number of credits student will earn from this class
13338:
1.297 matthew 13339: =back
13340:
1.191 harris41 13341:
13342: =item *
13343:
1.243 albertel 13344: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13345: custom role; give a custom role to a user for the level given by URL. Specify
13346: name and domain of role author, and role name
1.191 harris41 13347:
13348: =item *
13349:
1.243 albertel 13350: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13351:
13352: =item *
13353:
1.243 albertel 13354: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13355:
13356: =back
13357:
13358: =head2 Course Infomation
13359:
13360: =over 4
1.191 harris41 13361:
13362: =item *
13363:
1.1118 foxr 13364: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13365: specified course id, including all environment settings for the
13366: course, the description of the course will be in the hash under the
13367: key 'description'
1.191 harris41 13368:
1.1118 foxr 13369: $options is an optional parameter that if supplied is a hash reference that controls
13370: what how this function works. It has the following key/values:
13371:
13372: =over 4
13373:
13374: =item freshen_cache
13375:
13376: If defined, and the environment cache for the course is valid, it is
13377: returned in the returned hash.
13378:
13379: =item one_time
13380:
13381: If defined, the last cache time is set to _now_
13382:
13383: =item user
13384:
13385: If defined, the supplied username is used instead of the current user.
13386:
13387:
13388: =back
13389:
1.191 harris41 13390: =item *
13391:
1.624 albertel 13392: resdata($name,$domain,$type,@which) : request for current parameter
13393: setting for a specific $type, where $type is either 'course' or 'user',
13394: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 13395: answers for 10 minutes.
1.243 albertel 13396:
1.877 foxr 13397: =item *
13398:
13399: get_courseresdata($courseid, $domain) : dump the entire course resource
13400: data base, returning a hash that is keyed by the resource name and has
13401: values that are the resource value. I believe that the timestamps and
13402: versions are also returned.
13403:
1.1172.2.31 raeburn 13404: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13405: supplemental content area. This routine caches the number of files for
13406: 10 minutes.
13407:
1.243 albertel 13408: =back
13409:
13410: =head2 Course Modification
13411:
13412: =over 4
1.191 harris41 13413:
13414: =item *
13415:
1.243 albertel 13416: writecoursepref($courseid,%prefs) : write preferences (environment
13417: database) for a course
1.191 harris41 13418:
13419: =item *
13420:
1.1011 raeburn 13421: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13422:
13423: =item *
13424:
1.1038 raeburn 13425: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13426:
1.1167 droeschl 13427: =item *
13428:
13429: is_course($courseid), is_course($cdom, $cnum)
13430:
13431: Accepts either a combined $courseid (in the form of domain_courseid) or the
13432: two component version $cdom, $cnum. It checks if the specified course exists.
13433:
13434: Returns:
13435: undef if the course doesn't exist, otherwise
13436: in scalar context the combined courseid.
13437: in list context the two components of the course identifier, domain and
13438: courseid.
13439:
1.243 albertel 13440: =back
13441:
13442: =head2 Resource Subroutines
13443:
13444: =over 4
1.191 harris41 13445:
13446: =item *
13447:
1.243 albertel 13448: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13449:
13450: =item *
13451:
1.243 albertel 13452: repcopy($filename) : subscribes to the requested file, and attempts to
13453: replicate from the owning library server, Might return
1.607 raeburn 13454: 'unavailable', 'not_found', 'forbidden', 'ok', or
13455: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13456: resource. Expects the local filesystem pathname
13457: (/home/httpd/html/res/....)
13458:
13459: =back
13460:
13461: =head2 Resource Information
13462:
13463: =over 4
1.191 harris41 13464:
13465: =item *
13466:
1.1172.2.28 raeburn 13467: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13468: and returns the value of a variety of different possible values,
13469: $varname should be a request string, and the other parameters can be
13470: used to specify who and what one is asking about. Ordinarily, $cid
13471: does not need to be specified, as it is retrived from
13472: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13473: within lonuserstate::loadmap() when initializing a course, before
13474: $env{'request.course.id'} has been set, so it needs to be provided
13475: in that one case.
1.243 albertel 13476:
13477: Possible values for $varname are environment.lastname (or other item
13478: from the envirnment hash), user.name (or someother aspect about the
13479: user), resource.0.maxtries (or some other part and parameter of a
13480: resource)
1.204 albertel 13481:
13482: =item *
13483:
1.243 albertel 13484: directcondval($number) : get current value of a condition; reads from a state
13485: string
1.204 albertel 13486:
13487: =item *
13488:
1.243 albertel 13489: condval($condidx) : value of condition index based on state
1.204 albertel 13490:
13491: =item *
13492:
1.243 albertel 13493: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13494: resource's metadata, $what should be either a specific key, or either
13495: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13496: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13497:
13498: this function automatically caches all requests
1.191 harris41 13499:
13500: =item *
13501:
1.243 albertel 13502: metadata_query($query,$custom,$customshow) : make a metadata query against the
13503: network of library servers; returns file handle of where SQL and regex results
13504: will be stored for query
1.191 harris41 13505:
13506: =item *
13507:
1.1172.2.66 raeburn 13508: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
13509: return symbolic list entry (all arguments optional).
13510:
13511: Args: filename is the filename (including path) for the file for which a symb
13512: is required; donotrecurse, if true will prevent calls to allowed() being made
13513: to check access status if more than one resource was found in the bighash
13514: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
13515: a randompick); ignorecachednull, if true will prevent a symb of '' being
13516: returned if $env{$cache_str} is defined as ''; checkforblock if true will
13517: cause possible symbs to be checked to determine if they are subject to content
13518: blocking, if so they will not be included as possible symbs; possibles is a
13519: ref to a hash, which, as a side effect, will be populated with all possible
13520: symbs (content blocking not tested).
13521:
1.243 albertel 13522: returns the data handle
1.191 harris41 13523:
13524: =item *
13525:
1.1172.2.17 raeburn 13526: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 13527: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13528: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 13529: on failure, user must be in a course, as it assumes the existence of
13530: the course initial hash, and uses $env('request.course.id'}. The third
13531: arg is an optional reference to a scalar. If this arg is passed in the
13532: call to symbverify, it will be set to 1 if the symb has been set to be
13533: encrypted; otherwise it will be null.
1.243 albertel 13534:
1.191 harris41 13535: =item *
13536:
1.243 albertel 13537: symbclean($symb) : removes versions numbers from a symb, returns the
13538: cleaned symb
1.191 harris41 13539:
13540: =item *
13541:
1.243 albertel 13542: is_on_map($uri) : checks if the $uri is somewhere on the current
13543: course map, user must be in a course for it to work.
1.191 harris41 13544:
13545: =item *
13546:
1.243 albertel 13547: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13548:
13549: =item *
13550:
1.243 albertel 13551: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13552: a random seed, all arguments are optional, if they aren't sent it uses the
13553: environment to derive them. Note: if symb isn't sent and it can't get one
13554: from &symbread it will use the current time as its return value
1.191 harris41 13555:
13556: =item *
13557:
1.243 albertel 13558: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13559: unfakeable, receipt
1.191 harris41 13560:
13561: =item *
13562:
1.620 albertel 13563: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13564:
13565: =item *
13566:
1.243 albertel 13567: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13568:
13569: =item *
13570:
1.243 albertel 13571: 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 13572:
13573: =item *
13574:
1.243 albertel 13575: 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 13576:
13577: =item *
13578:
1.243 albertel 13579: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13580:
13581: =item *
13582:
1.243 albertel 13583: devalidate($symb) : devalidate temporary spreadsheet calculations,
13584: forcing spreadsheet to reevaluate the resource scores next time.
13585:
1.1172.2.13 raeburn 13586: =item *
13587:
13588: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13589: when viewing in course context.
13590:
13591: input: six args -- filename (decluttered), course number, course domain,
13592: url, symb (if registered) and group (if this is a
13593: group item -- e.g., bulletin board, group page etc.).
13594:
13595: output: array of five scalars --
13596: $cfile -- url for file editing if editable on current server
13597: $home -- homeserver of resource (i.e., for author if published,
13598: or course if uploaded.).
13599: $switchserver -- 1 if server switch will be needed.
13600: $forceedit -- 1 if icon/link should be to go to edit mode
13601: $forceview -- 1 if icon/link should be to go to view mode
13602:
13603: =item *
13604:
13605: is_course_upload($file,$cnum,$cdom)
13606:
13607: Used in course context to determine if current file was uploaded to
13608: the course (i.e., would be found in /userfiles/docs on the course's
13609: homeserver.
13610:
13611: input: 3 args -- filename (decluttered), course number and course domain.
13612: output: boolean -- 1 if file was uploaded.
13613:
1.243 albertel 13614: =back
13615:
13616: =head2 Storing/Retreiving Data
13617:
13618: =over 4
1.191 harris41 13619:
13620: =item *
13621:
1.1172.2.64 raeburn 13622: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13623: permanently for this url; hashref needs to be given and should be a \%hashname;
13624: the remaining args aren't required and if they aren't passed or are '' they will
13625: be derived from the env (with the exception of $laststore, which is an
13626: optional arg used when a user's submission is stored in grading).
13627: $laststore is $version=$timestamp, where $version is the most recent version
13628: number retrieved for the corresponding $symb in the $namespace db file, and
13629: $timestamp is the timestamp for that transaction (UNIX time).
13630: $laststore is currently only passed when cstore() is called by
13631: structuretags::finalize_storage().
1.191 harris41 13632:
13633: =item *
13634:
1.1172.2.64 raeburn 13635: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13636: but uses critical subroutine
1.191 harris41 13637:
13638: =item *
13639:
1.243 albertel 13640: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13641: all args are optional
1.191 harris41 13642:
13643: =item *
13644:
1.717 albertel 13645: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13646: dumps the complete (or key matching regexp) namespace into a hash
13647: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13648: normally &store()ed into
13649:
13650: $range should be either an integer '100' (give me the first 100
13651: matching records)
13652: or be two integers sperated by a - with no spaces
13653: '30-50' (give me the 30th through the 50th matching
13654: records)
13655:
13656:
13657: =item *
13658:
1.1172.2.59 raeburn 13659: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 13660: replaces a &store() version of data with a replacement set of data
13661: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 13662: reference. If $tolog is true, the transaction is logged in the courselog
13663: with an action=PUTSTORE.
1.717 albertel 13664:
13665: =item *
13666:
1.243 albertel 13667: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13668: works very similar to store/cstore, but all data is stored in a
13669: temporary location and can be reset using tmpreset, $storehash should
13670: be a hash reference, returns nothing on success
1.191 harris41 13671:
13672: =item *
13673:
1.243 albertel 13674: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13675: similar to restore, but all data is stored in a temporary location and
13676: can be reset using tmpreset. Returns a hash of values on success,
13677: error string otherwise.
1.191 harris41 13678:
13679: =item *
13680:
1.243 albertel 13681: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13682: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13683:
13684: =item *
13685:
1.243 albertel 13686: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13687: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13688:
13689: =item *
13690:
1.243 albertel 13691: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13692: namesp ($udom and $uname are optional)
1.191 harris41 13693:
13694: =item *
13695:
1.702 albertel 13696: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13697: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13698: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13699:
1.702 albertel 13700: $range should be either an integer '100' (give me the first 100
13701: matching records)
13702: or be two integers sperated by a - with no spaces
13703: '30-50' (give me the 30th through the 50th matching
13704: records)
1.449 matthew 13705: =item *
13706:
13707: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13708: $store can be a scalar, an array reference, or if the amount to be
13709: incremented is > 1, a hash reference.
13710:
13711: ($udom and $uname are optional)
1.191 harris41 13712:
13713: =item *
13714:
1.243 albertel 13715: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13716: ($udom and $uname are optional)
1.191 harris41 13717:
13718: =item *
13719:
1.243 albertel 13720: cput($namespace,$storehash,$udom,$uname) : critical put
13721: ($udom and $uname are optional)
1.191 harris41 13722:
13723: =item *
13724:
1.748 albertel 13725: newput($namespace,$storehash,$udom,$uname) :
13726:
13727: Attempts to store the items in the $storehash, but only if they don't
13728: currently exist, if this succeeds you can be certain that you have
13729: successfully created a new key value pair in the $namespace db.
13730:
13731:
13732: Args:
13733: $namespace: name of database to store values to
13734: $storehash: hashref to store to the db
13735: $udom: (optional) domain of user containing the db
13736: $uname: (optional) name of user caontaining the db
13737:
13738: Returns:
13739: 'ok' -> succeeded in storing all keys of $storehash
13740: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13741: least <key> already existed in the db (other
13742: requested keys may also already exist)
1.967 bisitz 13743: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13744: 'con_lost' -> unable to contact request server
13745: 'refused' -> action was not allowed by remote machine
13746:
13747:
13748: =item *
13749:
1.243 albertel 13750: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13751: reference filled in from namesp (encrypts the return communication)
13752: ($udom and $uname are optional)
1.191 harris41 13753:
13754: =item *
13755:
1.243 albertel 13756: log($udom,$name,$home,$message) : write to permanent log for user; use
13757: critical subroutine
13758:
1.806 raeburn 13759: =item *
13760:
1.860 raeburn 13761: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13762: array reference filled in from namespace found in domain level on either
13763: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13764:
13765: =item *
13766:
1.860 raeburn 13767: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13768: domain level either on specified domain server ($uhome) or primary domain
13769: server ($udom and $uhome are optional)
1.806 raeburn 13770:
1.943 raeburn 13771: =item *
13772:
1.1172.2.35 raeburn 13773: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13774: for: authentication, language, quotas, timezone, date locale, and portal URL in
13775: the target domain.
13776:
13777: May also include additional key => value pairs for the following groups:
13778:
13779: =over
13780:
13781: =item
13782: disk quotas (MB allocated by default to portfolios and authoring spaces).
13783:
13784: =over
13785:
13786: =item defaultquota, authorquota
13787:
13788: =back
13789:
13790: =item
13791: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13792: portfolio for users).
13793:
13794: =over
13795:
13796: =item
13797: aboutme, blog, webdav, portfolio
13798:
13799: =back
13800:
13801: =item
13802: requestcourses: ability to request courses, and how requests are processed.
13803:
13804: =over
13805:
13806: =item
1.1172.2.37 raeburn 13807: official, unofficial, community, textbook
1.1172.2.35 raeburn 13808:
13809: =back
13810:
13811: =item
13812: inststatus: types of institutional affiliation, and order in which they are displayed.
13813:
13814: =over
13815:
13816: =item
1.1172.2.44 raeburn 13817: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 13818:
13819: =back
13820:
13821: =item
13822: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13823: for course's uploaded content.
13824:
13825: =over
13826:
13827: =item
1.1172.2.68 raeburn 13828: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13829: communityquota, textbookquota
1.1172.2.35 raeburn 13830:
13831: =back
13832:
13833: =item
13834: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13835: on your servers.
13836:
13837: =over
13838:
13839: =item
13840: remotesessions, hostedsessions
13841:
13842: =back
13843:
13844: =back
13845:
13846: In cases where a domain coordinator has never used the "Set Domain Configuration"
13847: utility to create a configuration.db file on a domain's primary library server
13848: only the following domain defaults: auth_def, auth_arg_def, lang_def
13849: -- corresponding values are authentication type (internal, krb4, krb5,
13850: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13851: will be available. Values are retrieved from cache (if current), unless the
13852: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13853: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13854:
13855: Typical usage:
1.943 raeburn 13856:
1.1172.2.35 raeburn 13857: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13858:
1.243 albertel 13859: =back
13860:
13861: =head2 Network Status Functions
13862:
13863: =over 4
1.191 harris41 13864:
13865: =item *
13866:
1.1137 raeburn 13867: dirlist() : return directory list based on URI (first arg).
13868:
13869: Inputs: 1 required, 5 optional.
13870:
13871: =over
13872:
13873: =item
13874: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13875:
13876: =item
13877: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13878:
13879: =item
13880: $username - username of user/course to be listed. Extracted from $uri if absent.
13881:
13882: =item
13883: $getpropath - boolean: 1 if prepend path using &propath().
13884:
13885: =item
13886: $getuserdir - boolean: 1 if prepend path for "userfiles".
13887:
13888: =item
13889: $alternateRoot - path to prepend in place of path from $uri.
13890:
13891: =back
13892:
13893: Returns: Array of up to two items.
13894:
13895: =over
13896:
13897: a reference to an array of files/subdirectories
13898:
13899: =over
13900:
13901: Each element in the array of files/subdirectories is a & separated list of
13902: item name and the result of running stat on the item. If dirlist was requested
13903: for a file instead of a directory, the item name will be ''. For a directory
13904: listing, if the item is a metadata file, the element will end &N&M
13905: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13906: default copyright set (1).
13907:
13908: =back
13909:
13910: a scalar containing error condition (if encountered).
13911:
13912: =over
13913:
13914: =item
13915: no_host (no homeserver identified for $username:$domain).
13916:
13917: =item
13918: no_such_host (server contacted for listing not identified as valid host).
13919:
13920: =item
13921: con_lost (connection to remote server failed).
13922:
13923: =item
13924: refused (invalid $username:$domain received on lond side).
13925:
13926: =item
13927: no_such_dir (directory at specified path on lond side does not exist).
13928:
13929: =item
13930: empty (directory at specified path on lond side is empty).
13931:
13932: =over
13933:
13934: This is currently not encountered because the &ls3, &ls2,
13935: &ls (_handler) routines on the lond side do not filter out
13936: . and .. from a directory listing.
13937:
13938: =back
13939:
13940: =back
13941:
13942: =back
1.191 harris41 13943:
13944: =item *
13945:
1.243 albertel 13946: spareserver() : find server with least workload from spare.tab
13947:
1.986 foxr 13948:
13949: =item *
13950:
13951: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13952: if there is no corresponding loncapa host.
13953:
1.243 albertel 13954: =back
13955:
1.986 foxr 13956:
1.243 albertel 13957: =head2 Apache Request
13958:
13959: =over 4
1.191 harris41 13960:
13961: =item *
13962:
1.243 albertel 13963: ssi($url,%hash) : server side include, does a complete request cycle on url to
13964: localhost, posts hash
13965:
13966: =back
13967:
13968: =head2 Data to String to Data
13969:
13970: =over 4
1.191 harris41 13971:
13972: =item *
13973:
1.243 albertel 13974: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13975: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13976:
13977: =item *
13978:
1.243 albertel 13979: hashref2str($hashref) : convert a hashref into a string complete with
13980: escaping and '=' and '&' separators, supports elements that are
13981: arrayrefs and hashrefs
1.191 harris41 13982:
13983: =item *
13984:
1.243 albertel 13985: arrayref2str($arrayref) : convert an arrayref into a string complete
13986: with escaping and '&' separators, supports elements that are arrayrefs
13987: and hashrefs
1.191 harris41 13988:
13989: =item *
13990:
1.243 albertel 13991: str2hash($string) : convert string to hash using unescaping and
13992: splitting on '=' and '&', supports elements that are arrayrefs and
13993: hashrefs
1.191 harris41 13994:
13995: =item *
13996:
1.243 albertel 13997: str2array($string) : convert string to hash using unescaping and
13998: splitting on '&', supports elements that are arrayrefs and hashrefs
13999:
14000: =back
14001:
14002: =head2 Logging Routines
14003:
14004:
14005: These routines allow one to make log messages in the lonnet.log and
14006: lonnet.perm logfiles.
1.191 harris41 14007:
1.1119 foxr 14008: =over 4
14009:
1.191 harris41 14010: =item *
14011:
1.243 albertel 14012: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14013:
14014: =item *
14015:
1.243 albertel 14016: logthis() : append message to the normal lonnet.log file, it gets
14017: preiodically rolled over and deleted.
1.191 harris41 14018:
14019: =item *
14020:
1.243 albertel 14021: logperm() : append a permanent message to lonnet.perm.log, this log
14022: file never gets deleted by any automated portion of the system, only
14023: messages of critical importance should go in here.
14024:
1.1119 foxr 14025:
1.243 albertel 14026: =back
14027:
14028: =head2 General File Helper Routines
14029:
14030: =over 4
1.191 harris41 14031:
14032: =item *
14033:
1.481 raeburn 14034: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14035: (a) files in /uploaded
14036: (i) If a local copy of the file exists -
14037: compares modification date of local copy with last-modified date for
14038: definitive version stored on home server for course. If local copy is
14039: stale, requests a new version from the home server and stores it.
14040: If the original has been removed from the home server, then local copy
14041: is unlinked.
14042: (ii) If local copy does not exist -
14043: requests the file from the home server and stores it.
14044:
14045: If $caller is 'uploadrep':
14046: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14047: for request for files originally uploaded via DOCS.
14048: - returns 'ok' if fresh local copy now available, -1 otherwise.
14049:
14050: Otherwise:
14051: This indicates a call from the content generation phase of the request.
14052: - returns the entire contents of the file or -1.
14053:
14054: (b) files in /res
14055: - returns the entire contents of a file or -1;
14056: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14057:
1.712 albertel 14058:
14059: =item *
14060:
14061: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14062: reference
14063:
14064: returns either a stat() list of data about the file or an empty list
14065: if the file doesn't exist or couldn't find out about it (connection
14066: problems or user unknown)
14067:
1.191 harris41 14068: =item *
14069:
1.243 albertel 14070: filelocation($dir,$file) : returns file system location of a file
14071: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14072: directory that relative $file lookups are to looked in ($dir of /a/dir
14073: and a file of ../bob will become /a/bob)
1.191 harris41 14074:
14075: =item *
14076:
14077: hreflocation($dir,$file) : returns file system location or a URL; same as
14078: filelocation except for hrefs
14079:
14080: =item *
14081:
1.1172.2.49 raeburn 14082: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14083: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14084:
1.243 albertel 14085: =back
14086:
1.608 albertel 14087: =head2 Usererfile file routines (/uploaded*)
14088:
14089: =over 4
14090:
14091: =item *
14092:
14093: userfileupload(): main rotine for putting a file in a user or course's
14094: filespace, arguments are,
14095:
1.620 albertel 14096: formname - required - this is the name of the element in $env where the
1.608 albertel 14097: filename, and the contents of the file to create/modifed exist
1.620 albertel 14098: the filename is in $env{'form.'.$formname.'.filename'} and the
14099: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14100: context - if coursedoc, store the file in the course of the active role
14101: of the current user;
14102: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14103: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14104: subdir - required - subdirectory to put the file in under ../userfiles/
14105: if undefined, it will be placed in "unknown"
14106:
14107: (This routine calls clean_filename() to remove any dangerous
14108: characters from the filename, and then calls finuserfileupload() to
14109: complete the transaction)
14110:
14111: returns either the url of the uploaded file (/uploaded/....) if successful
14112: and /adm/notfound.html if unsuccessful
14113:
14114: =item *
14115:
14116: clean_filename(): routine for cleaing a filename up for storage in
14117: userfile space, argument is:
14118:
14119: filename - proposed filename
14120:
14121: returns: the new clean filename
14122:
14123: =item *
14124:
1.1090 raeburn 14125: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14126: userspace, probably shouldn't be called directly
14127:
14128: docuname: username or courseid of destination for the file
14129: docudom: domain of user/course of destination for the file
14130: formname: same as for userfileupload()
1.1090 raeburn 14131: fname: filename (including subdirectories) for the file
14132: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14133: allfiles: reference to hash used to store objects found by parser
14134: codebase: reference to hash used for codebases of java objects found by parser
14135: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14136: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14137: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14138: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14139: context: if 'overwrite', will move the uploaded file from its temporary location to
14140: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14141: mimetype: reference to scalar to accommodate mime type determined
14142: from File::MMagic if $parser = parse.
1.608 albertel 14143:
14144: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14145: and /adm/notfound.html if unsuccessful (or an error message if context
14146: was 'overwrite').
14147:
1.608 albertel 14148:
14149: =item *
14150:
14151: renameuserfile(): renames an existing userfile to a new name
14152:
14153: Args:
14154: docuname: username or courseid of destination for the file
14155: docudom: domain of user/course of destination for the file
14156: old: current file name (including any subdirs under userfiles)
14157: new: desired file name (including any subdirs under userfiles)
14158:
14159: =item *
14160:
14161: mkdiruserfile(): creates a directory is a userfiles dir
14162:
14163: Args:
14164: docuname: username or courseid of destination for the file
14165: docudom: domain of user/course of destination for the file
14166: dir: dir to create (including any subdirs under userfiles)
14167:
14168: =item *
14169:
14170: removeuserfile(): removes a file that exists in userfiles
14171:
14172: Args:
14173: docuname: username or courseid of destination for the file
14174: docudom: domain of user/course of destination for the file
14175: fname: filname to delete (including any subdirs under userfiles)
14176:
14177: =item *
14178:
14179: removeuploadedurl(): convience function for removeuserfile()
14180:
14181: Args:
14182: url: a full /uploaded/... url to delete
14183:
1.747 albertel 14184: =item *
14185:
14186: get_portfile_permissions():
14187: Args:
14188: domain: domain of user or course contain the portfolio files
14189: user: name of user or num of course contain the portfolio files
14190: Returns:
14191: hashref of a dump of the proper file_permissions.db
14192:
14193:
14194: =item *
14195:
14196: get_access_controls():
14197:
14198: Args:
14199: current_permissions: the hash ref returned from get_portfile_permissions()
14200: group: (optional) the group you want the files associated with
14201: file: (optional) the file you want access info on
14202:
14203: Returns:
1.749 raeburn 14204: a hash (keys are file names) of hashes containing
14205: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14206: values are XML containing access control settings (see below)
1.747 albertel 14207:
14208: Internal notes:
14209:
1.749 raeburn 14210: access controls are stored in file_permissions.db as key=value pairs.
14211: key -> path to file/file_name\0uniqueID:scope_end_start
14212: where scope -> public,guest,course,group,domains or users.
14213: end -> UNIX time for end of access (0 -> no end date)
14214: start -> UNIX time for start of access
14215:
14216: value -> XML description of access control
14217: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14218: <start></start>
14219: <end></end>
14220:
14221: <password></password> for scope type = guest
14222:
14223: <domain></domain> for scope type = course or group
14224: <number></number>
14225: <roles id="">
14226: <role></role>
14227: <access></access>
14228: <section></section>
14229: <group></group>
14230: </roles>
14231:
14232: <dom></dom> for scope type = domains
14233:
14234: <users> for scope type = users
14235: <user>
14236: <uname></uname>
14237: <udom></udom>
14238: </user>
14239: </users>
14240: </scope>
14241:
14242: Access data is also aggregated for each file in an additional key=value pair:
14243: key -> path to file/file_name\0accesscontrol
14244: value -> reference to hash
14245: hash contains key = value pairs
14246: where key = uniqueID:scope_end_start
14247: value = UNIX time record was last updated
14248:
14249: Used to improve speed of look-ups of access controls for each file.
14250:
14251: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14252:
1.1172.2.13 raeburn 14253: =item *
14254:
1.749 raeburn 14255: modify_access_controls():
14256:
14257: Modifies access controls for a portfolio file
14258: Args
14259: 1. file name
14260: 2. reference to hash of required changes,
14261: 3. domain
14262: 4. username
14263: where domain,username are the domain of the portfolio owner
14264: (either a user or a course)
14265:
14266: Returns:
14267: 1. result of additions or updates ('ok' or 'error', with error message).
14268: 2. result of deletions ('ok' or 'error', with error message).
14269: 3. reference to hash of any new or updated access controls.
14270: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14271: key = integer (inbound ID)
1.1172.2.13 raeburn 14272: value = uniqueID
14273:
14274: =item *
14275:
14276: get_timebased_id():
14277:
14278: Attempts to get a unique timestamp-based suffix for use with items added to a
14279: course via the Course Editor (e.g., folders, composite pages,
14280: group bulletin boards).
14281:
14282: Args: (first three required; six others optional)
14283:
14284: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14285: docssequence, or name of group
14286:
14287: 2. keyid (alphanumeric): name of temporary locking key in hash,
14288: e.g., num, boardids
14289:
14290: 3. namespace: name of gdbm file used to store suffixes already assigned;
14291: file will be named nohist_namespace.db
14292:
14293: 4. cdom: domain of course; default is current course domain from %env
14294:
14295: 5. cnum: course number; default is current course number from %env
14296:
14297: 6. idtype: set to concat if an additional digit is to be appended to the
14298: unix timestamp to form the suffix, if the plain timestamp is already
14299: in use. Default is to not do this, but simply increment the unix
14300: timestamp by 1 until a unique key is obtained.
14301:
14302: 7. who: holder of locking key; defaults to user:domain for user.
14303:
14304: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14305: retrying); default is 3.
14306:
14307: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14308:
14309: Returns:
14310:
14311: 1. suffix obtained (numeric)
14312:
14313: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14314:
14315: 3. error: contains (localized) error message if an error occurred.
14316:
1.747 albertel 14317:
1.608 albertel 14318: =back
14319:
1.243 albertel 14320: =head2 HTTP Helper Routines
14321:
14322: =over 4
14323:
1.191 harris41 14324: =item *
14325:
14326: escape() : unpack non-word characters into CGI-compatible hex codes
14327:
14328: =item *
14329:
14330: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14331:
1.243 albertel 14332: =back
14333:
14334: =head1 PRIVATE SUBROUTINES
14335:
14336: =head2 Underlying communication routines (Shouldn't call)
14337:
14338: =over 4
14339:
14340: =item *
14341:
14342: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14343:
14344: =item *
14345:
14346: reply() : uses subreply to send a message to remote machine, logs all failures
14347:
14348: =item *
14349:
14350: critical() : passes a critical message to another server; if cannot
14351: get through then place message in connection buffer directory and
14352: returns con_delayed, if incapable of saving message, returns
14353: con_failed
14354:
14355: =item *
14356:
14357: reconlonc() : tries to reconnect lonc client processes.
14358:
14359: =back
14360:
14361: =head2 Resource Access Logging
14362:
14363: =over 4
14364:
14365: =item *
14366:
14367: flushcourselogs() : flush (save) buffer logs and access logs
14368:
14369: =item *
14370:
14371: courselog($what) : save message for course in hash
14372:
14373: =item *
14374:
14375: courseacclog($what) : save message for course using &courselog(). Perform
14376: special processing for specific resource types (problems, exams, quizzes, etc).
14377:
1.191 harris41 14378: =item *
14379:
14380: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14381: as a PerlChildExitHandler
1.243 albertel 14382:
14383: =back
14384:
14385: =head2 Other
14386:
14387: =over 4
14388:
14389: =item *
14390:
14391: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14392:
14393: =back
14394:
14395: =cut
1.877 foxr 14396:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>