Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.70
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.70! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.69 2016/08/05 11:14:06 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.1172.2.36 raeburn 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
1.871 albertel 81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 85: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 86:
1.1 albertel 87: use IO::Socket;
1.31 www 88: use GDBM_File;
1.208 albertel 89: use HTML::LCParser;
1.88 www 90: use Fcntl qw(:flock);
1.870 albertel 91: use Storable qw(thaw nfreeze);
1.539 albertel 92: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 93: use Cache::Memcached;
1.676 albertel 94: use Digest::MD5;
1.790 albertel 95: use Math::Random;
1.1024 raeburn 96: use File::MMagic;
1.807 albertel 97: use LONCAPA qw(:DEFAULT :match);
1.740 www 98: use LONCAPA::Configuration;
1.1160 www 99: use LONCAPA::lonmetadata;
1.1172.2.22 raeburn 100: use LONCAPA::Lond;
1.1117 foxr 101:
1.1090 raeburn 102: use File::Copy;
1.676 albertel 103:
1.195 www 104: my $readit;
1.550 foxr 105: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 106:
1.619 albertel 107: require Exporter;
108:
109: our @ISA = qw (Exporter);
110: our @EXPORT = qw(%env);
111:
1.1172.2.9 raeburn 112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 113: {
114: my $logid;
1.1172.2.9 raeburn 115: sub write_log {
116: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
117: if ($context eq 'course') {
118: if (($cnum eq '') || ($cdom eq '')) {
119: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
120: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
121: }
1.957 raeburn 122: }
1.1172.2.13 raeburn 123: $logid ++;
1.957 raeburn 124: my $now = time();
125: my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9 raeburn 126: my $logentry = {
127: $id => {
128: 'exe_uname' => $env{'user.name'},
129: 'exe_udom' => $env{'user.domain'},
130: 'exe_time' => $now,
131: 'exe_ip' => $ENV{'REMOTE_ADDR'},
132: 'delflag' => $delflag,
133: 'logentry' => $storehash,
134: 'uname' => $uname,
135: 'udom' => $udom,
136: }
137: };
138: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 139: }
140: }
1.1 albertel 141:
1.163 harris41 142: sub logtouch {
143: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 144: unless (-e "$execdir/logs/lonnet.log") {
145: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 146: close $fh;
147: }
148: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
149: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
150: }
151:
1.1 albertel 152: sub logthis {
153: my $message=shift;
154: my $execdir=$perlvar{'lonDaemons'};
155: my $now=time;
156: my $local=localtime($now);
1.448 albertel 157: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 158: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
159: print $fh $logstring;
1.448 albertel 160: close($fh);
161: }
1.1 albertel 162: return 1;
163: }
164:
165: sub logperm {
166: my $message=shift;
167: my $execdir=$perlvar{'lonDaemons'};
168: my $now=time;
169: my $local=localtime($now);
1.448 albertel 170: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
171: print $fh "$now:$message:$local\n";
172: close($fh);
173: }
1.1 albertel 174: return 1;
175: }
176:
1.850 albertel 177: sub create_connection {
1.853 albertel 178: my ($hostname,$lonid) = @_;
1.851 albertel 179: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 180: Type => SOCK_STREAM,
181: Timeout => 10);
182: return 0 if (!$client);
1.890 albertel 183: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 184: my $result = <$client>;
185: chomp($result);
186: return 1 if ($result eq 'done');
187: return 0;
188: }
189:
1.983 raeburn 190: sub get_server_timezone {
191: my ($cnum,$cdom) = @_;
192: my $home=&homeserver($cnum,$cdom);
193: if ($home ne 'no_host') {
194: my $cachetime = 24*3600;
195: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
196: if (defined($cached)) {
197: return $timezone;
198: } else {
199: my $timezone = &reply('servertimezone',$home);
200: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
201: }
202: }
203: }
1.850 albertel 204:
1.1106 raeburn 205: sub get_server_distarch {
206: my ($lonhost,$ignore_cache) = @_;
207: if (defined($lonhost)) {
208: if (!defined(&hostname($lonhost))) {
209: return;
210: }
211: my $cachetime = 12*3600;
212: if (!$ignore_cache) {
213: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
214: if (defined($cached)) {
215: return $distarch;
216: }
217: }
218: my $rep = &reply('serverdistarch',$lonhost);
219: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
220: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
221: $rep eq '') {
222: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
223: }
224: }
225: return;
226: }
227:
1.993 raeburn 228: sub get_server_loncaparev {
1.1073 raeburn 229: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 230: if (defined($lonhost)) {
231: if (!defined(&hostname($lonhost))) {
232: undef($lonhost);
233: }
234: }
235: if (!defined($lonhost)) {
236: if (defined(&domain($dom,'primary'))) {
237: $lonhost=&domain($dom,'primary');
238: if ($lonhost eq 'no_host') {
239: undef($lonhost);
240: }
241: }
242: }
243: if (defined($lonhost)) {
1.1073 raeburn 244: my $cachetime = 12*3600;
245: if (!$ignore_cache) {
246: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
247: if (defined($cached)) {
248: return $loncaparev;
249: }
250: }
251: my ($answer,$loncaparev);
252: my @ids=¤t_machine_ids();
253: if (grep(/^\Q$lonhost\E$/,@ids)) {
254: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 255: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 256: $loncaparev = $1;
257: }
258: } else {
259: $answer = &reply('serverloncaparev',$lonhost);
260: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
261: if ($caller eq 'loncron') {
262: my $ua=new LWP::UserAgent;
1.1082 raeburn 263: $ua->timeout(4);
1.1073 raeburn 264: my $protocol = $protocol{$lonhost};
265: $protocol = 'http' if ($protocol ne 'https');
266: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
267: my $request=new HTTP::Request('GET',$url);
268: my $response=$ua->request($request);
269: unless ($response->is_error()) {
270: my $content = $response->content;
1.1081 raeburn 271: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 272: $loncaparev = $1;
273: }
274: }
275: } else {
276: $loncaparev = $loncaparevs{$lonhost};
277: }
1.1081 raeburn 278: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 279: $loncaparev = $1;
280: }
1.993 raeburn 281: }
1.1073 raeburn 282: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 283: }
284: }
285:
1.1074 raeburn 286: sub get_server_homeID {
287: my ($hostname,$ignore_cache,$caller) = @_;
288: unless ($ignore_cache) {
289: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
290: if (defined($cached)) {
291: return $serverhomeID;
292: }
293: }
294: my $cachetime = 12*3600;
295: my $serverhomeID;
296: if ($caller eq 'loncron') {
297: my @machine_ids = &machine_ids($hostname);
298: foreach my $id (@machine_ids) {
299: my $response = &reply('serverhomeID',$id);
300: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
301: $serverhomeID = $response;
302: last;
303: }
304: }
305: if ($serverhomeID eq '') {
306: $serverhomeID = $machine_ids[-1];
307: }
308: } else {
309: $serverhomeID = $serverhomeIDs{$hostname};
310: }
311: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
312: }
313:
1.1121 raeburn 314: sub get_remote_globals {
315: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 316: my ($result,%returnhash,%whatneeded);
317: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 318: foreach my $what (sort(keys(%{$whathash}))) {
319: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 320: my ($response,$cached);
1.1121 raeburn 321: unless ($ignore_cache) {
1.1125 raeburn 322: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 323: }
324: if (defined($cached)) {
1.1125 raeburn 325: $returnhash{$what} = $response;
1.1121 raeburn 326: } else {
1.1125 raeburn 327: $whatneeded{$what} = 1;
1.1121 raeburn 328: }
329: }
1.1125 raeburn 330: if (keys(%whatneeded) == 0) {
331: $result = 'ok';
332: } else {
1.1121 raeburn 333: my $requested = &freeze_escape(\%whatneeded);
334: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 335: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
336: ($rep eq 'unknown_cmd')) {
337: $result = $rep;
338: } else {
339: $result = 'ok';
1.1121 raeburn 340: my @pairs=split(/\&/,$rep);
1.1125 raeburn 341: foreach my $item (@pairs) {
342: my ($key,$value)=split(/=/,$item,2);
343: my $what = &unescape($key);
344: my $hashid = $lonhost.'-'.$what;
345: $returnhash{$what}=&thaw_unescape($value);
346: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 347: }
348: }
349: }
350: }
1.1125 raeburn 351: return ($result,\%returnhash);
1.1121 raeburn 352: }
353:
1.1124 raeburn 354: sub remote_devalidate_cache {
1.1172.2.35 raeburn 355: my ($lonhost,$cachekeys) = @_;
356: my $items;
357: return unless (ref($cachekeys) eq 'ARRAY');
358: my $cachestr = join('&',@{$cachekeys});
359: return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 360: }
361:
1.1 albertel 362: # -------------------------------------------------- Non-critical communication
363: sub subreply {
364: my ($cmd,$server)=@_;
1.838 albertel 365: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 366: #
367: # With loncnew process trimming, there's a timing hole between lonc server
368: # process exit and the master server picking up the listen on the AF_UNIX
369: # socket. In that time interval, a lock file will exist:
370:
371: my $lockfile=$peerfile.".lock";
372: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
373: sleep(1);
374: }
375: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 376: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 377: #
1.550 foxr 378: # We'll give the connection a few tries before abandoning it. If
379: # connection is not possible, we'll con_lost back to the client.
380: #
381: my $client;
382: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
383: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
384: Type => SOCK_STREAM,
385: Timeout => 10);
1.869 albertel 386: if ($client) {
1.550 foxr 387: last; # Connected!
1.850 albertel 388: } else {
1.853 albertel 389: &create_connection(&hostname($server),$server);
1.550 foxr 390: }
1.850 albertel 391: sleep(1); # Try again later if failed connection.
1.550 foxr 392: }
393: my $answer;
394: if ($client) {
1.704 albertel 395: print $client "sethost:$server:$cmd\n";
1.550 foxr 396: $answer=<$client>;
397: if (!$answer) { $answer="con_lost"; }
398: chomp($answer);
399: } else {
400: $answer = 'con_lost'; # Failed connection.
401: }
1.1 albertel 402: return $answer;
403: }
404:
405: sub reply {
406: my ($cmd,$server)=@_;
1.838 albertel 407: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 408: my $answer=subreply($cmd,$server);
1.65 www 409: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 410: &logthis("<font color=\"blue\">WARNING:".
1.12 www 411: " $cmd to $server returned $answer</font>");
412: }
1.1 albertel 413: return $answer;
414: }
415:
416: # ----------------------------------------------------------- Send USR1 to lonc
417:
418: sub reconlonc {
1.891 albertel 419: my ($lonid) = @_;
420: my $hostname = &hostname($lonid);
421: if ($lonid) {
422: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
423: if ($hostname && -e $peerfile) {
424: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
425: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
426: Type => SOCK_STREAM,
427: Timeout => 10);
428: if ($client) {
429: print $client ("reset_retries\n");
430: my $answer=<$client>;
431: #reset just this one.
432: }
433: }
434: return;
435: }
436:
1.836 www 437: &logthis("Trying to reconnect lonc");
1.1 albertel 438: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 439: if (open(my $fh,"<$loncfile")) {
1.1 albertel 440: my $loncpid=<$fh>;
441: chomp($loncpid);
442: if (kill 0 => $loncpid) {
443: &logthis("lonc at pid $loncpid responding, sending USR1");
444: kill USR1 => $loncpid;
445: sleep 1;
1.836 www 446: } else {
1.12 www 447: &logthis(
1.672 albertel 448: "<font color=\"blue\">WARNING:".
1.12 www 449: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 450: }
451: } else {
1.836 www 452: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 453: }
454: }
455:
456: # ------------------------------------------------------ Critical communication
1.12 www 457:
1.1 albertel 458: sub critical {
459: my ($cmd,$server)=@_;
1.838 albertel 460: unless (&hostname($server)) {
1.672 albertel 461: &logthis("<font color=\"blue\">WARNING:".
1.89 www 462: " Critical message to unknown server ($server)</font>");
463: return 'no_such_host';
464: }
1.1 albertel 465: my $answer=reply($cmd,$server);
466: if ($answer eq 'con_lost') {
467: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 468: my $answer=reply($cmd,$server);
1.1 albertel 469: if ($answer eq 'con_lost') {
470: my $now=time;
471: my $middlename=$cmd;
1.5 www 472: $middlename=substr($middlename,0,16);
1.1 albertel 473: $middlename=~s/\W//g;
474: my $dfilename=
1.305 www 475: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
476: $dumpcount++;
1.1 albertel 477: {
1.448 albertel 478: my $dfh;
479: if (open($dfh,">$dfilename")) {
480: print $dfh "$cmd\n";
481: close($dfh);
482: }
1.1 albertel 483: }
484: sleep 2;
485: my $wcmd='';
486: {
1.448 albertel 487: my $dfh;
488: if (open($dfh,"<$dfilename")) {
489: $wcmd=<$dfh>;
490: close($dfh);
491: }
1.1 albertel 492: }
493: chomp($wcmd);
1.7 www 494: if ($wcmd eq $cmd) {
1.672 albertel 495: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 496: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 497: &logperm("D:$server:$cmd");
498: return 'con_delayed';
499: } else {
1.672 albertel 500: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 501: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 502: &logperm("F:$server:$cmd");
503: return 'con_failed';
504: }
505: }
506: }
507: return $answer;
1.405 albertel 508: }
509:
1.755 albertel 510: # ------------------------------------------- check if return value is an error
511:
512: sub error {
513: my ($result) = @_;
1.756 albertel 514: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 515: if ($2 == 2) { return undef; }
516: return $1;
517: }
518: return undef;
519: }
520:
1.783 albertel 521: sub convert_and_load_session_env {
522: my ($lonidsdir,$handle)=@_;
523: my @profile;
524: {
1.917 albertel 525: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
526: if (!$opened) {
1.915 albertel 527: return 0;
528: }
1.783 albertel 529: flock($idf,LOCK_SH);
530: @profile=<$idf>;
531: close($idf);
532: }
533: my %temp_env;
534: foreach my $line (@profile) {
1.786 albertel 535: if ($line !~ m/=/) {
536: return 0;
537: }
1.783 albertel 538: chomp($line);
539: my ($envname,$envvalue)=split(/=/,$line,2);
540: $temp_env{&unescape($envname)} = &unescape($envvalue);
541: }
542: unlink("$lonidsdir/$handle.id");
543: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
544: 0640)) {
545: %disk_env = %temp_env;
546: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
547: untie(%disk_env);
548: }
1.786 albertel 549: return 1;
1.783 albertel 550: }
551:
1.374 www 552: # ------------------------------------------- Transfer profile into environment
1.780 albertel 553: my $env_loaded;
554: sub transfer_profile_to_env {
1.788 albertel 555: my ($lonidsdir,$handle,$force_transfer) = @_;
556: if (!$force_transfer && $env_loaded) { return; }
1.374 www 557:
1.720 albertel 558: if (!defined($lonidsdir)) {
559: $lonidsdir = $perlvar{'lonIDsDir'};
560: }
561: if (!defined($handle)) {
562: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
563: }
564:
1.786 albertel 565: my $convert;
566: {
1.917 albertel 567: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
568: if (!$opened) {
1.915 albertel 569: return;
570: }
1.786 albertel 571: flock($idf,LOCK_SH);
572: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
573: &GDBM_READER(),0640)) {
574: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
575: untie(%disk_env);
576: } else {
577: $convert = 1;
578: }
579: }
580: if ($convert) {
581: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
582: &logthis("Failed to load session, or convert session.");
583: }
1.374 www 584: }
1.783 albertel 585:
1.786 albertel 586: my %remove;
1.783 albertel 587: while ( my $envname = each(%env) ) {
1.433 matthew 588: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
589: if ($time < time-300) {
1.783 albertel 590: $remove{$key}++;
1.433 matthew 591: }
592: }
593: }
1.783 albertel 594:
1.619 albertel 595: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 596: $env_loaded=1;
1.783 albertel 597: foreach my $expired_key (keys(%remove)) {
1.433 matthew 598: &delenv($expired_key);
1.374 www 599: }
1.1 albertel 600: }
601:
1.916 albertel 602: # ---------------------------------------------------- Check for valid session
603: sub check_for_valid_session {
1.1172.2.36 raeburn 604: my ($r,$name,$userhashref) = @_;
1.916 albertel 605: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 606: if ($name eq '') {
607: $name = 'lonID';
608: }
609: my $lonid=$cookies{$name};
1.916 albertel 610: return undef if (!$lonid);
611:
612: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 613: my $lonidsdir;
614: if ($name eq 'lonDAV') {
615: $lonidsdir=$r->dir_config('lonDAVsessDir');
616: } else {
617: $lonidsdir=$r->dir_config('lonIDsDir');
618: }
1.916 albertel 619: return undef if (!-e "$lonidsdir/$handle.id");
620:
1.917 albertel 621: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
622: return undef if (!$opened);
1.916 albertel 623:
624: flock($idf,LOCK_SH);
625: my %disk_env;
626: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
627: &GDBM_READER(),0640)) {
628: return undef;
629: }
630:
631: if (!defined($disk_env{'user.name'})
632: || !defined($disk_env{'user.domain'})) {
633: return undef;
634: }
1.1172.2.18 raeburn 635:
1.1172.2.36 raeburn 636: if (ref($userhashref) eq 'HASH') {
637: $userhashref->{'name'} = $disk_env{'user.name'};
638: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18 raeburn 639: }
640:
1.916 albertel 641: return $handle;
642: }
643:
1.830 albertel 644: sub timed_flock {
645: my ($file,$lock_type) = @_;
646: my $failed=0;
647: eval {
648: local $SIG{__DIE__}='DEFAULT';
649: local $SIG{ALRM}=sub {
650: $failed=1;
651: die("failed lock");
652: };
653: alarm(13);
654: flock($file,$lock_type);
655: alarm(0);
656: };
657: if ($failed) {
658: return undef;
659: } else {
660: return 1;
661: }
662: }
663:
1.5 www 664: # ---------------------------------------------------------- Append Environment
665:
666: sub appenv {
1.949 raeburn 667: my ($newenv,$roles) = @_;
668: if (ref($newenv) eq 'HASH') {
669: foreach my $key (keys(%{$newenv})) {
670: my $refused = 0;
671: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
672: $refused = 1;
673: if (ref($roles) eq 'ARRAY') {
1.1172.2.40 raeburn 674: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 675: if (grep(/^\Q$role\E$/,@{$roles})) {
676: $refused = 0;
677: }
678: }
679: }
680: if ($refused) {
681: &logthis("<font color=\"blue\">WARNING: ".
682: "Attempt to modify environment ".$key." to ".$newenv->{$key}
683: .'</font>');
684: delete($newenv->{$key});
685: } else {
686: $env{$key}=$newenv->{$key};
687: }
688: }
689: my $opened = open(my $env_file,'+<',$env{'user.environment'});
690: if ($opened
691: && &timed_flock($env_file,LOCK_EX)
692: &&
693: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
694: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
695: while (my ($key,$value) = each(%{$newenv})) {
696: $disk_env{$key} = $value;
697: }
698: untie(%disk_env);
1.35 www 699: }
1.191 harris41 700: }
1.56 www 701: return 'ok';
702: }
703: # ----------------------------------------------------- Delete from Environment
704:
705: sub delenv {
1.1104 raeburn 706: my ($delthis,$regexp,$roles) = @_;
707: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
708: my $refused = 1;
709: if (ref($roles) eq 'ARRAY') {
710: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
711: if (grep(/^\Q$role\E$/,@{$roles})) {
712: $refused = 0;
713: }
714: }
715: if ($refused) {
716: &logthis("<font color=\"blue\">WARNING: ".
717: "Attempt to delete from environment ".$delthis);
718: return 'error';
719: }
1.56 www 720: }
1.917 albertel 721: my $opened = open(my $env_file,'+<',$env{'user.environment'});
722: if ($opened
1.915 albertel 723: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 724: &&
725: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
726: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 727: foreach my $key (keys(%disk_env)) {
1.987 raeburn 728: if ($regexp) {
729: if ($key=~/^$delthis/) {
730: delete($env{$key});
731: delete($disk_env{$key});
732: }
733: } else {
734: if ($key=~/^\Q$delthis\E/) {
735: delete($env{$key});
736: delete($disk_env{$key});
737: }
738: }
1.448 albertel 739: }
1.783 albertel 740: untie(%disk_env);
1.5 www 741: }
742: return 'ok';
1.369 albertel 743: }
744:
1.790 albertel 745: sub get_env_multiple {
746: my ($name) = @_;
747: my @values;
748: if (defined($env{$name})) {
749: # exists is it an array
750: if (ref($env{$name})) {
751: @values=@{ $env{$name} };
752: } else {
753: $values[0]=$env{$name};
754: }
755: }
756: return(@values);
757: }
758:
1.958 www 759: # ------------------------------------------------------------------- Locking
760:
761: sub set_lock {
762: my ($text)=@_;
763: $locknum++;
764: my $id=$$.'-'.$locknum;
765: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
766: 'session.lock.'.$id => $text});
767: return $id;
768: }
769:
770: sub get_locks {
771: my $num=0;
772: my %texts=();
773: foreach my $lock (split(/\,/,$env{'session.locks'})) {
774: if ($lock=~/\w/) {
775: $num++;
776: $texts{$lock}=$env{'session.lock.'.$lock};
777: }
778: }
779: return ($num,%texts);
780: }
781:
782: sub remove_lock {
783: my ($id)=@_;
784: my $newlocks='';
785: foreach my $lock (split(/\,/,$env{'session.locks'})) {
786: if (($lock=~/\w/) && ($lock ne $id)) {
787: $newlocks.=','.$lock;
788: }
789: }
790: &appenv({'session.locks' => $newlocks});
791: &delenv('session.lock.'.$id);
792: }
793:
794: sub remove_all_locks {
795: my $activelocks=$env{'session.locks'};
796: foreach my $lock (split(/\,/,$env{'session.locks'})) {
797: if ($lock=~/\w/) {
798: &remove_lock($lock);
799: }
800: }
801: }
802:
803:
1.369 albertel 804: # ------------------------------------------ Find out current server userload
805: sub userload {
806: my $numusers=0;
807: {
808: opendir(LONIDS,$perlvar{'lonIDsDir'});
809: my $filename;
810: my $curtime=time;
811: while ($filename=readdir(LONIDS)) {
1.925 albertel 812: next if ($filename eq '.' || $filename eq '..');
813: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 814: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 815: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 816: }
817: closedir(LONIDS);
818: }
819: my $userloadpercent=0;
820: my $maxuserload=$perlvar{'lonUserLoadLim'};
821: if ($maxuserload) {
1.371 albertel 822: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 823: }
1.372 albertel 824: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 825: return $userloadpercent;
1.283 www 826: }
827:
1.1 albertel 828: # ------------------------------ Find server with least workload from spare.tab
1.11 www 829:
1.1 albertel 830: sub spareserver {
1.1083 raeburn 831: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 832: my $spare_server;
1.370 albertel 833: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 834: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
835: : $userloadpercent;
1.1083 raeburn 836: my ($uint_dom,$remotesessions);
837: if (($udom ne '') && (&domain($udom) ne '')) {
838: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
839: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
840: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
841: $remotesessions = $udomdefaults{'remotesessions'};
842: }
1.1123 raeburn 843: my $spareshash = &this_host_spares($udom);
844: if (ref($spareshash) eq 'HASH') {
845: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
846: foreach my $try_server (@{ $spareshash->{'primary'} }) {
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)) {
1557: my $idlist=join('&',@ids);
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]) {
1567: $returnhash{$ids[$i]}=$answer[$i];
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.672 albertel 10067: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 10068: " Trying to get resource data for ".
10069: $uname." at ".$udom.": ".
10070: $tmp."</font>");
10071: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10072: #&EXT_cache_set($udom,$uname);
10073: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10074: undef($tmp); # not really an error so don't send it back
1.624 albertel 10075: }
10076: return $tmp;
10077: }
1.879 foxr 10078: #----------------------------------------------- resdata - return resource data
10079: # Purpose:
10080: # Return resource data for either users or for a course.
10081: # Parameters:
10082: # $name - Course/user name.
10083: # $domain - Name of the domain the user/course is registered on.
10084: # $type - Type of thing $name is (must be 'course' or 'user'
10085: # @which - Array of names of resources desired.
10086: # Returns:
10087: # The value of the first reasource in @which that is found in the
10088: # resource hash.
10089: # Exceptional Conditions:
10090: # If the $type passed in is not valid (not the string 'course' or
10091: # 'user', an undefined reference is returned.
10092: # If none of the resources are found, an undef is returned
1.624 albertel 10093: sub resdata {
10094: my ($name,$domain,$type,@which)=@_;
10095: my $result;
10096: if ($type eq 'course') {
10097: $result=&get_courseresdata($name,$domain);
10098: } elsif ($type eq 'user') {
10099: $result=&get_userresdata($name,$domain);
10100: }
10101: if (!ref($result)) { return $result; }
1.251 albertel 10102: foreach my $item (@which) {
1.927 albertel 10103: if (defined($result->{$item->[0]})) {
10104: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10105: }
1.250 albertel 10106: }
1.291 albertel 10107: return undef;
1.200 www 10108: }
10109:
1.1172.2.31 raeburn 10110: sub get_numsuppfiles {
10111: my ($cnum,$cdom,$ignorecache)=@_;
10112: my $hashid=$cnum.':'.$cdom;
10113: my ($suppcount,$cached);
10114: unless ($ignorecache) {
10115: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10116: }
10117: unless (defined($cached)) {
10118: my $chome=&homeserver($cnum,$cdom);
10119: unless ($chome eq 'no_host') {
10120: ($suppcount,my $errors) = (0,0);
10121: my $suppmap = 'supplemental.sequence';
10122: ($suppcount,$errors) =
10123: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10124: }
10125: &do_cache_new('suppcount',$hashid,$suppcount,600);
10126: }
10127: return $suppcount;
10128: }
10129:
1.379 matthew 10130: #
10131: # EXT resource caching routines
10132: #
10133:
10134: sub clear_EXT_cache_status {
1.383 albertel 10135: &delenv('cache.EXT.');
1.379 matthew 10136: }
10137:
10138: sub EXT_cache_status {
10139: my ($target_domain,$target_user) = @_;
1.383 albertel 10140: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10141: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10142: # We know already the user has no data
10143: return 1;
10144: } else {
10145: return 0;
10146: }
10147: }
10148:
10149: sub EXT_cache_set {
10150: my ($target_domain,$target_user) = @_;
1.383 albertel 10151: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10152: #&appenv({$cachename => time});
1.379 matthew 10153: }
10154:
1.28 www 10155: # --------------------------------------------------------- Value of a Variable
1.58 www 10156: sub EXT {
1.715 albertel 10157:
1.1172.2.28 raeburn 10158: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10159: unless ($varname) { return ''; }
1.218 albertel 10160: #get real user name/domain, courseid and symb
10161: my $courseid;
1.359 albertel 10162: my $publicuser;
1.427 www 10163: if ($symbparm) {
10164: $symbparm=&get_symb_from_alias($symbparm);
10165: }
1.218 albertel 10166: if (!($uname && $udom)) {
1.790 albertel 10167: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10168: if (!$symbparm) { $symbparm=$cursymb; }
10169: } else {
1.620 albertel 10170: $courseid=$env{'request.course.id'};
1.218 albertel 10171: }
1.48 www 10172: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10173: my $rest;
1.320 albertel 10174: if (defined($therest[0])) {
1.48 www 10175: $rest=join('.',@therest);
10176: } else {
10177: $rest='';
10178: }
1.320 albertel 10179:
1.57 www 10180: my $qualifierrest=$qualifier;
10181: if ($rest) { $qualifierrest.='.'.$rest; }
10182: my $spacequalifierrest=$space;
10183: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10184: if ($realm eq 'user') {
1.48 www 10185: # --------------------------------------------------------------- user.resource
10186: if ($space eq 'resource') {
1.651 albertel 10187: if ( (defined($Apache::lonhomework::parsing_a_problem)
10188: || defined($Apache::lonhomework::parsing_a_task))
10189: &&
1.744 albertel 10190: ($symbparm eq &symbread()) ) {
10191: # if we are in the middle of processing the resource the
10192: # get the value we are planning on committing
10193: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10194: return $Apache::lonhomework::results{$qualifierrest};
10195: } else {
10196: return $Apache::lonhomework::history{$qualifierrest};
10197: }
1.335 albertel 10198: } else {
1.359 albertel 10199: my %restored;
1.620 albertel 10200: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10201: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10202: } else {
10203: %restored=&restore($symbparm,$courseid,$udom,$uname);
10204: }
1.335 albertel 10205: return $restored{$qualifierrest};
10206: }
1.48 www 10207: # ----------------------------------------------------------------- user.access
10208: } elsif ($space eq 'access') {
1.218 albertel 10209: # FIXME - not supporting calls for a specific user
1.48 www 10210: return &allowed($qualifier,$rest);
10211: # ------------------------------------------ user.preferences, user.environment
10212: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10213: if (($uname eq $env{'user.name'}) &&
10214: ($udom eq $env{'user.domain'})) {
10215: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10216: } else {
1.359 albertel 10217: my %returnhash;
10218: if (!$publicuser) {
10219: %returnhash=&userenvironment($udom,$uname,
10220: $qualifierrest);
10221: }
1.218 albertel 10222: return $returnhash{$qualifierrest};
10223: }
1.48 www 10224: # ----------------------------------------------------------------- user.course
10225: } elsif ($space eq 'course') {
1.218 albertel 10226: # FIXME - not supporting calls for a specific user
1.620 albertel 10227: return $env{join('.',('request.course',$qualifier))};
1.48 www 10228: # ------------------------------------------------------------------- user.role
10229: } elsif ($space eq 'role') {
1.218 albertel 10230: # FIXME - not supporting calls for a specific user
1.620 albertel 10231: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10232: if ($qualifier eq 'value') {
10233: return $role;
10234: } elsif ($qualifier eq 'extent') {
10235: return $where;
10236: }
10237: # ----------------------------------------------------------------- user.domain
10238: } elsif ($space eq 'domain') {
1.218 albertel 10239: return $udom;
1.48 www 10240: # ------------------------------------------------------------------- user.name
10241: } elsif ($space eq 'name') {
1.218 albertel 10242: return $uname;
1.48 www 10243: # ---------------------------------------------------- Any other user namespace
1.29 www 10244: } else {
1.359 albertel 10245: my %reply;
10246: if (!$publicuser) {
10247: %reply=&get($space,[$qualifierrest],$udom,$uname);
10248: }
10249: return $reply{$qualifierrest};
1.48 www 10250: }
1.236 www 10251: } elsif ($realm eq 'query') {
10252: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10253: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10254: [$spacequalifierrest]);
1.620 albertel 10255: return $env{'form.'.$spacequalifierrest};
1.236 www 10256: } elsif ($realm eq 'request') {
1.48 www 10257: # ------------------------------------------------------------- request.browser
10258: if ($space eq 'browser') {
1.1145 bisitz 10259: return $env{'browser.'.$qualifier};
1.57 www 10260: # ------------------------------------------------------------ request.filename
10261: } else {
1.620 albertel 10262: return $env{'request.'.$spacequalifierrest};
1.29 www 10263: }
1.28 www 10264: } elsif ($realm eq 'course') {
1.48 www 10265: # ---------------------------------------------------------- course.description
1.620 albertel 10266: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10267: } elsif ($realm eq 'resource') {
1.165 www 10268:
1.620 albertel 10269: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10270: if (!$symbparm) { $symbparm=&symbread(); }
10271: }
1.693 albertel 10272:
1.1172.2.30 raeburn 10273: if ($qualifier eq '') {
10274: if ($space eq 'title') {
10275: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10276: return &gettitle($symbparm);
10277: }
1.693 albertel 10278:
1.1172.2.30 raeburn 10279: if ($space eq 'map') {
10280: my ($map) = &decode_symb($symbparm);
10281: return &symbread($map);
10282: }
10283: if ($space eq 'maptitle') {
10284: my ($map) = &decode_symb($symbparm);
10285: return &gettitle($map);
10286: }
10287: if ($space eq 'filename') {
10288: if ($symbparm) {
10289: return &clutter((&decode_symb($symbparm))[2]);
10290: }
10291: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10292: }
1.1172.2.30 raeburn 10293:
10294: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10295: if ($space eq 'visibleparts') {
10296: my $navmap = Apache::lonnavmaps::navmap->new();
10297: my $item;
10298: if (ref($navmap)) {
10299: my $res = $navmap->getBySymb($symbparm);
10300: my $parts = $res->parts();
10301: if (ref($parts) eq 'ARRAY') {
10302: $item = join(',',@{$parts});
10303: }
10304: undef($navmap);
10305: }
10306: return $item;
10307: }
10308: }
10309: }
1.693 albertel 10310:
10311: my ($section, $group, @groups);
1.593 albertel 10312: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 10313: if (($courseid eq '') && ($cid)) {
10314: $courseid = $cid;
10315: }
10316: if (($symbparm && $courseid) &&
10317: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10318:
1.218 albertel 10319: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10320:
1.60 www 10321: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10322: my $symbp=$symbparm;
1.735 albertel 10323: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10324:
10325: my $symbparm=$symbp.'.'.$spacequalifierrest;
10326: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10327:
1.620 albertel 10328: if (($env{'user.name'} eq $uname) &&
10329: ($env{'user.domain'} eq $udom)) {
10330: $section=$env{'request.course.sec'};
1.733 raeburn 10331: @groups = split(/:/,$env{'request.course.groups'});
10332: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10333: } else {
1.539 albertel 10334: if (! defined($usection)) {
1.551 albertel 10335: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10336: } else {
10337: $section = $usection;
10338: }
1.733 raeburn 10339: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10340: }
10341:
10342: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10343: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10344: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10345:
1.593 albertel 10346: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10347: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 10348: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10349:
1.60 www 10350: # ----------------------------------------------------------- first, check user
1.624 albertel 10351:
10352: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 10353: ([$courselevelr,'resource'],
10354: [$courselevelm,'map' ],
10355: [$courselevel, 'course' ]));
1.931 albertel 10356: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10357:
1.594 albertel 10358: # ------------------------------------------------ second, check some of course
1.684 raeburn 10359: my $coursereply;
1.691 raeburn 10360: if (@groups > 0) {
10361: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10362: $mapparm,$spacequalifierrest);
1.927 albertel 10363: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10364: }
1.96 www 10365:
1.684 raeburn 10366: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10367: $env{'course.'.$courseid.'.domain'},
10368: 'course',
10369: ([$seclevelr, 'resource'],
10370: [$seclevelm, 'map' ],
10371: [$seclevel, 'course' ],
10372: [$courselevelr,'resource']));
10373: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10374:
1.60 www 10375: # ------------------------------------------------------ third, check map parms
1.218 albertel 10376: my %parmhash=();
10377: my $thisparm='';
10378: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10379: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10380: &GDBM_READER(),0640)) {
1.218 albertel 10381: $thisparm=$parmhash{$symbparm};
10382: untie(%parmhash);
10383: }
1.927 albertel 10384: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10385: }
1.594 albertel 10386: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10387:
1.218 albertel 10388: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10389: my $filename;
10390: if (!$symbparm) { $symbparm=&symbread(); }
10391: if ($symbparm) {
1.409 www 10392: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10393: } else {
1.620 albertel 10394: $filename=$env{'request.filename'};
1.282 albertel 10395: }
10396: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10397: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10398: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10399: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10400:
1.927 albertel 10401: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10402: if ($symbparm && defined($courseid) &&
1.620 albertel 10403: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10404: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10405: $env{'course.'.$courseid.'.domain'},
10406: 'course',
1.927 albertel 10407: ([$courselevelm,'map' ],
10408: [$courselevel, 'course']));
10409: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10410: }
1.145 www 10411: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10412: unless ($space eq '0') {
1.336 albertel 10413: my @parts=split(/_/,$space);
10414: my $id=pop(@parts);
10415: my $part=join('_',@parts);
10416: if ($part eq '') { $part='0'; }
1.927 albertel 10417: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10418: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10419: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10420: }
1.395 albertel 10421: if ($recurse) { return undef; }
10422: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10423: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10424: # ---------------------------------------------------- Any other user namespace
10425: } elsif ($realm eq 'environment') {
10426: # ----------------------------------------------------------------- environment
1.620 albertel 10427: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10428: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10429: } else {
1.770 albertel 10430: if ($uname eq 'anonymous' && $udom eq '') {
10431: return '';
10432: }
1.219 albertel 10433: my %returnhash=&userenvironment($udom,$uname,
10434: $spacequalifierrest);
10435: return $returnhash{$spacequalifierrest};
10436: }
1.28 www 10437: } elsif ($realm eq 'system') {
1.48 www 10438: # ----------------------------------------------------------------- system.time
10439: if ($space eq 'time') {
10440: return time;
10441: }
1.696 albertel 10442: } elsif ($realm eq 'server') {
10443: # ----------------------------------------------------------------- system.time
10444: if ($space eq 'name') {
10445: return $ENV{'SERVER_NAME'};
10446: }
1.28 www 10447: }
1.48 www 10448: return '';
1.61 www 10449: }
10450:
1.927 albertel 10451: sub get_reply {
10452: my ($reply_value) = @_;
1.940 raeburn 10453: if (ref($reply_value) eq 'ARRAY') {
10454: if (wantarray) {
10455: return @$reply_value;
10456: }
10457: return $reply_value->[0];
10458: } else {
10459: return $reply_value;
1.927 albertel 10460: }
10461: }
10462:
1.691 raeburn 10463: sub check_group_parms {
10464: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10465: my @groupitems = ();
10466: my $resultitem;
1.927 albertel 10467: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10468: foreach my $group (@{$groups}) {
10469: foreach my $level (@levels) {
1.927 albertel 10470: my $item = $courseid.'.['.$group.'].'.$level->[0];
10471: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10472: }
10473: }
10474: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10475: $env{'course.'.$courseid.'.domain'},
10476: 'course',@groupitems);
10477: return $coursereply;
10478: }
10479:
10480: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10481: my ($courseid,@groups) = @_;
10482: @groups = sort(@groups);
1.691 raeburn 10483: return @groups;
10484: }
10485:
1.395 albertel 10486: sub packages_tab_default {
10487: my ($uri,$varname)=@_;
10488: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10489:
10490: my (@extension,@specifics,$do_default);
10491: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10492: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10493: if ($pack_type eq 'default') {
10494: $do_default=1;
10495: } elsif ($pack_type eq 'extension') {
10496: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10497: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10498: # only look at packages defaults for packages that this id is
1.738 albertel 10499: push(@specifics,[$package,$pack_type,$pack_part]);
10500: }
10501: }
10502: # first look for a package that matches the requested part id
10503: foreach my $package (@specifics) {
10504: my (undef,$pack_type,$pack_part)=@{$package};
10505: next if ($pack_part ne $part);
10506: if (defined($packagetab{"$pack_type&$name&default"})) {
10507: return $packagetab{"$pack_type&$name&default"};
10508: }
10509: }
10510: # look for any possible matching non extension_ package
10511: foreach my $package (@specifics) {
10512: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10513: if (defined($packagetab{"$pack_type&$name&default"})) {
10514: return $packagetab{"$pack_type&$name&default"};
10515: }
1.585 albertel 10516: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10517: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10518: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10519: }
10520: }
1.738 albertel 10521: # look for any posible extension_ match
10522: foreach my $package (@extension) {
10523: my ($package,$pack_type)=@{$package};
10524: if (defined($packagetab{"$pack_type&$name&default"})) {
10525: return $packagetab{"$pack_type&$name&default"};
10526: }
10527: if (defined($packagetab{$package."&$name&default"})) {
10528: return $packagetab{$package."&$name&default"};
10529: }
10530: }
10531: # look for a global default setting
10532: if ($do_default && defined($packagetab{"default&$name&default"})) {
10533: return $packagetab{"default&$name&default"};
10534: }
1.395 albertel 10535: return undef;
10536: }
10537:
1.334 albertel 10538: sub add_prefix_and_part {
10539: my ($prefix,$part)=@_;
10540: my $keyroot;
10541: if (defined($prefix) && $prefix !~ /^__/) {
10542: # prefix that has a part already
10543: $keyroot=$prefix;
10544: } elsif (defined($prefix)) {
10545: # prefix that is missing a part
10546: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10547: } else {
10548: # no prefix at all
10549: if (defined($part)) { $keyroot='_'.$part; }
10550: }
10551: return $keyroot;
10552: }
10553:
1.71 www 10554: # ---------------------------------------------------------------- Get metadata
10555:
1.599 albertel 10556: my %metaentry;
1.1070 www 10557: my %importedpartids;
1.71 www 10558: sub metadata {
1.176 www 10559: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10560: $uri=&declutter($uri);
1.288 albertel 10561: # if it is a non metadata possible uri return quickly
1.529 albertel 10562: if (($uri eq '') ||
10563: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 10564: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10565: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10566: return undef;
10567: }
1.1172.2.49 raeburn 10568: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 10569: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10570: return undef;
1.288 albertel 10571: }
1.73 www 10572: my $filename=$uri;
10573: $uri=~s/\.meta$//;
1.172 www 10574: #
10575: # Is the metadata already cached?
1.177 www 10576: # Look at timestamp of caching
1.172 www 10577: # Everything is cached by the main uri, libraries are never directly cached
10578: #
1.428 albertel 10579: if (!defined($liburi)) {
1.599 albertel 10580: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10581: if (defined($cached)) { return $result->{':'.$what}; }
10582: }
10583: {
1.1069 www 10584: # Imported parts would go here
1.1070 www 10585: my %importedids=();
10586: my @origfileimportpartids=();
1.1069 www 10587: my $importedparts=0;
1.172 www 10588: #
10589: # Is this a recursive call for a library?
10590: #
1.599 albertel 10591: # if (! exists($metacache{$uri})) {
10592: # $metacache{$uri}={};
10593: # }
1.924 albertel 10594: my $cachetime = 60*60;
1.171 www 10595: if ($liburi) {
10596: $liburi=&declutter($liburi);
10597: $filename=$liburi;
1.401 bowersj2 10598: } else {
1.599 albertel 10599: &devalidate_cache_new('meta',$uri);
10600: undef(%metaentry);
1.401 bowersj2 10601: }
1.140 www 10602: my %metathesekeys=();
1.73 www 10603: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10604: my $metastring;
1.1140 www 10605: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10606: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10607: $metastring =
1.929 albertel 10608: &Apache::lonnet::ssi_body($which,
1.924 albertel 10609: ('grade_target' => 'meta'));
10610: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10611: } elsif (($uri !~ m -^(editupload)/-) &&
10612: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10613: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10614: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10615: $metastring=&getfile($file);
1.489 albertel 10616: }
1.208 albertel 10617: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10618: my $token;
1.140 www 10619: undef %metathesekeys;
1.71 www 10620: while ($token=$parser->get_token) {
1.339 albertel 10621: if ($token->[0] eq 'S') {
10622: if (defined($token->[2]->{'package'})) {
1.172 www 10623: #
10624: # This is a package - get package info
10625: #
1.339 albertel 10626: my $package=$token->[2]->{'package'};
10627: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10628: if (defined($token->[2]->{'id'})) {
10629: $keyroot.='_'.$token->[2]->{'id'};
10630: }
1.599 albertel 10631: if ($metaentry{':packages'}) {
10632: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10633: } else {
1.599 albertel 10634: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10635: }
1.736 albertel 10636: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10637: my $part=$keyroot;
10638: $part=~s/^\_//;
1.736 albertel 10639: if ($pack_entry=~/^\Q$package\E\&/ ||
10640: $pack_entry=~/^\Q$package\E_0\&/) {
10641: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10642: # ignore package.tab specified default values
10643: # here &package_tab_default() will fetch those
10644: if ($subp eq 'default') { next; }
1.736 albertel 10645: my $value=$packagetab{$pack_entry};
1.432 albertel 10646: my $unikey;
10647: if ($pack =~ /_0$/) {
10648: $unikey='parameter_0_'.$name;
10649: $part=0;
10650: } else {
10651: $unikey='parameter'.$keyroot.'_'.$name;
10652: }
1.339 albertel 10653: if ($subp eq 'display') {
10654: $value.=' [Part: '.$part.']';
10655: }
1.599 albertel 10656: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10657: $metathesekeys{$unikey}=1;
1.599 albertel 10658: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10659: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10660: }
1.599 albertel 10661: if (defined($metaentry{':'.$unikey.'.default'})) {
10662: $metaentry{':'.$unikey}=
10663: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10664: }
1.339 albertel 10665: }
10666: }
10667: } else {
1.172 www 10668: #
10669: # This is not a package - some other kind of start tag
1.339 albertel 10670: #
10671: my $entry=$token->[1];
1.1068 www 10672: my $unikey='';
1.175 www 10673:
1.339 albertel 10674: if ($entry eq 'import') {
1.175 www 10675: #
10676: # Importing a library here
1.339 albertel 10677: #
1.1067 www 10678: my $location=$parser->get_text('/import');
10679: my $dir=$filename;
10680: $dir=~s|[^/]*$||;
10681: $location=&filelocation($dir,$location);
1.1069 www 10682:
1.1068 www 10683: my $importmode=$token->[2]->{'importmode'};
10684: if ($importmode eq 'problem') {
1.1069 www 10685: # Import as problem/response
1.1068 www 10686: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10687: } elsif ($importmode eq 'part') {
10688: # Import as part(s)
1.1069 www 10689: $importedparts=1;
10690: # We need to get the original file and the imported file to get the part order correct
10691: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10692: # Load and inspect original file
1.1070 www 10693: if ($#origfileimportpartids<0) {
10694: undef(%importedpartids);
10695: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10696: my $origfile=&getfile($origfilelocation);
10697: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10698: }
10699:
1.1069 www 10700: # Load and inspect imported file
10701: my $impfile=&getfile($location);
10702: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10703: if ($#impfilepartids>=0) {
10704: # This problem had parts
1.1070 www 10705: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10706: } else {
10707: # Importing by turning a single problem into a problem part
10708: # It gets the import-tags ID as part-ID
10709: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10710: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10711: }
1.1068 www 10712: } else {
10713: # Normal import
10714: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10715: if (defined($token->[2]->{'id'})) {
10716: $unikey.='_'.$token->[2]->{'id'};
10717: }
1.1067 www 10718: }
10719:
1.339 albertel 10720: if ($depthcount<20) {
1.736 albertel 10721: my $metadata =
10722: &metadata($uri,'keys', $location,$unikey,
10723: $depthcount+1);
10724: foreach my $meta (split(',',$metadata)) {
10725: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10726: $metathesekeys{$meta}=1;
1.339 albertel 10727: }
1.1068 www 10728:
10729: }
1.1067 www 10730: } else {
10731: #
10732: # Not importing, some other kind of non-package, non-library start tag
10733: #
10734: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10735: if (defined($token->[2]->{'id'})) {
10736: $unikey.='_'.$token->[2]->{'id'};
10737: }
1.339 albertel 10738: if (defined($token->[2]->{'name'})) {
10739: $unikey.='_'.$token->[2]->{'name'};
10740: }
10741: $metathesekeys{$unikey}=1;
1.736 albertel 10742: foreach my $param (@{$token->[3]}) {
10743: $metaentry{':'.$unikey.'.'.$param} =
10744: $token->[2]->{$param};
1.339 albertel 10745: }
10746: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10747: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10748: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10749: # only ws inside the tag, and not in default, so use default
10750: # as value
1.599 albertel 10751: $metaentry{':'.$unikey}=$default;
1.908 albertel 10752: } elsif ( $internaltext =~ /\S/ ) {
10753: # something interesting inside the tag
10754: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10755: } else {
1.908 albertel 10756: # no interesting values, don't set a default
1.339 albertel 10757: }
1.172 www 10758: # end of not-a-package not-a-library import
1.339 albertel 10759: }
1.172 www 10760: # end of not-a-package start tag
1.339 albertel 10761: }
1.172 www 10762: # the next is the end of "start tag"
1.339 albertel 10763: }
10764: }
1.483 albertel 10765: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10766: $extension = lc($extension);
10767: if ($extension eq 'htm') { $extension='html'; }
10768:
1.737 albertel 10769: foreach my $key (keys(%packagetab)) {
1.483 albertel 10770: #no specific packages #how's our extension
10771: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10772: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10773: \%metathesekeys);
10774: }
1.883 albertel 10775:
10776: if (!exists($metaentry{':packages'})
10777: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10778: foreach my $key (keys(%packagetab)) {
1.483 albertel 10779: #no specific packages well let's get default then
10780: if ($key!~/^default&/) { next; }
1.488 albertel 10781: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10782: \%metathesekeys);
10783: }
10784: }
1.338 www 10785: # are there custom rights to evaluate
1.599 albertel 10786: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10787:
1.338 www 10788: #
10789: # Importing a rights file here
1.339 albertel 10790: #
10791: unless ($depthcount) {
1.599 albertel 10792: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10793: my $dir=$filename;
10794: $dir=~s|[^/]*$||;
10795: $location=&filelocation($dir,$location);
1.736 albertel 10796: my $rights_metadata =
10797: &metadata($uri,'keys',$location,'_rights',
10798: $depthcount+1);
10799: foreach my $rights (split(',',$rights_metadata)) {
10800: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10801: $metathesekeys{$rights}=1;
1.339 albertel 10802: }
10803: }
10804: }
1.737 albertel 10805: # uniqifiy package listing
10806: my %seen;
10807: my @uniq_packages =
10808: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10809: $metaentry{':packages'} = join(',',@uniq_packages);
10810:
1.1070 www 10811: if ($importedparts) {
10812: # We had imported parts and need to rebuild partorder
10813: $metaentry{':partorder'}='';
10814: $metathesekeys{'partorder'}=1;
10815: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10816: if ($origfileimportpartids[$index] eq 'part') {
10817: # original part, part of the problem
10818: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10819: } else {
10820: # we have imported parts at this position
10821: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10822: }
10823: }
10824: $metaentry{':partorder'}=~s/^\,//;
10825: }
10826:
1.737 albertel 10827: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10828: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 10829: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 10830: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10831: # this is the end of "was not already recently cached
1.71 www 10832: }
1.599 albertel 10833: return $metaentry{':'.$what};
1.261 albertel 10834: }
10835:
1.488 albertel 10836: sub metadata_create_package_def {
1.483 albertel 10837: my ($uri,$key,$package,$metathesekeys)=@_;
10838: my ($pack,$name,$subp)=split(/\&/,$key);
10839: if ($subp eq 'default') { next; }
10840:
1.599 albertel 10841: if (defined($metaentry{':packages'})) {
10842: $metaentry{':packages'}.=','.$package;
1.483 albertel 10843: } else {
1.599 albertel 10844: $metaentry{':packages'}=$package;
1.483 albertel 10845: }
10846: my $value=$packagetab{$key};
10847: my $unikey;
10848: $unikey='parameter_0_'.$name;
1.599 albertel 10849: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10850: $$metathesekeys{$unikey}=1;
1.599 albertel 10851: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10852: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10853: }
1.599 albertel 10854: if (defined($metaentry{':'.$unikey.'.default'})) {
10855: $metaentry{':'.$unikey}=
10856: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10857: }
10858: }
10859:
1.261 albertel 10860: sub metadata_generate_part0 {
10861: my ($metadata,$metacache,$uri) = @_;
10862: my %allnames;
1.737 albertel 10863: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10864: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10865: my $part=$$metacache{':'.$metakey.'.part'};
10866: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10867: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10868: $allnames{$name}=$part;
10869: }
10870: }
10871: }
10872: foreach my $name (keys(%allnames)) {
10873: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10874: my $key=":parameter_0_$name";
1.261 albertel 10875: $$metacache{"$key.part"}='0';
10876: $$metacache{"$key.name"}=$name;
1.428 albertel 10877: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10878: $allnames{$name}.'_'.$name.
10879: '.type'};
1.428 albertel 10880: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10881: '.display'};
1.644 www 10882: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10883: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10884: $$metacache{"$key.display"}=$olddis;
10885: }
1.71 www 10886: }
10887:
1.764 albertel 10888: # ------------------------------------------------------ Devalidate title cache
10889:
10890: sub devalidate_title_cache {
10891: my ($url)=@_;
10892: if (!$env{'request.course.id'}) { return; }
10893: my $symb=&symbread($url);
10894: if (!$symb) { return; }
10895: my $key=$env{'request.course.id'}."\0".$symb;
10896: &devalidate_cache_new('title',$key);
10897: }
10898:
1.1014 droeschl 10899: # ------------------------------------------------- Get the title of a course
10900:
10901: sub current_course_title {
10902: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10903: }
1.301 www 10904: # ------------------------------------------------- Get the title of a resource
10905:
10906: sub gettitle {
10907: my $urlsymb=shift;
10908: my $symb=&symbread($urlsymb);
1.534 albertel 10909: if ($symb) {
1.620 albertel 10910: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10911: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10912: if (defined($cached)) {
10913: return $result;
10914: }
1.534 albertel 10915: my ($map,$resid,$url)=&decode_symb($symb);
10916: my $title='';
1.907 albertel 10917: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10918: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10919: } else {
10920: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10921: &GDBM_READER(),0640)) {
10922: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10923: $title=$bighash{'title_'.$mapid.'.'.$resid};
10924: untie(%bighash);
10925: }
1.534 albertel 10926: }
10927: $title=~s/\&colon\;/\:/gs;
10928: if ($title) {
1.1159 www 10929: # Remember both $symb and $title for dynamic metadata
10930: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10931: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10932: # Cache this title and then return it
1.599 albertel 10933: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10934: }
10935: $urlsymb=$url;
10936: }
10937: my $title=&metadata($urlsymb,'title');
10938: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10939: return $title;
1.301 www 10940: }
1.613 albertel 10941:
1.614 albertel 10942: sub get_slot {
10943: my ($which,$cnum,$cdom)=@_;
10944: if (!$cnum || !$cdom) {
1.790 albertel 10945: (undef,my $courseid)=&whichuser();
1.620 albertel 10946: $cdom=$env{'course.'.$courseid.'.domain'};
10947: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10948: }
1.703 albertel 10949: my $key=join("\0",'slots',$cdom,$cnum,$which);
10950: my %slotinfo;
10951: if (exists($remembered{$key})) {
10952: $slotinfo{$which} = $remembered{$key};
10953: } else {
10954: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10955: &Apache::lonhomework::showhash(%slotinfo);
10956: my ($tmp)=keys(%slotinfo);
10957: if ($tmp=~/^error:/) { return (); }
10958: $remembered{$key} = $slotinfo{$which};
10959: }
1.616 albertel 10960: if (ref($slotinfo{$which}) eq 'HASH') {
10961: return %{$slotinfo{$which}};
10962: }
10963: return $slotinfo{$which};
1.614 albertel 10964: }
1.1150 raeburn 10965:
10966: sub get_reservable_slots {
10967: my ($cnum,$cdom,$uname,$udom) = @_;
10968: my $now = time;
10969: my $reservable_info;
10970: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10971: if (exists($remembered{$key})) {
10972: $reservable_info = $remembered{$key};
10973: } else {
10974: my %resv;
10975: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10976: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10977: $reservable_info = \%resv;
10978: $remembered{$key} = $reservable_info;
10979: }
10980: return $reservable_info;
10981: }
10982:
10983: sub get_course_slots {
10984: my ($cnum,$cdom) = @_;
10985: my $hashid=$cnum.':'.$cdom;
10986: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10987: if (defined($cached)) {
10988: if (ref($result) eq 'HASH') {
10989: return %{$result};
10990: }
10991: } else {
10992: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10993: my ($tmp) = keys(%slots);
10994: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 10995: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10996: return %slots;
10997: }
10998: }
10999: return;
11000: }
11001:
11002: sub devalidate_slots_cache {
11003: my ($cnum,$cdom)=@_;
11004: my $hashid=$cnum.':'.$cdom;
11005: &devalidate_cache_new('allslots',$hashid);
11006: }
11007:
1.1172.2.8 raeburn 11008: sub get_coursechange {
11009: my ($cdom,$cnum) = @_;
11010: if ($cdom eq '' || $cnum eq '') {
11011: return unless ($env{'request.course.id'});
11012: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11013: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11014: }
11015: my $hashid=$cdom.'_'.$cnum;
11016: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11017: if ((defined($cached)) && ($change ne '')) {
11018: return $change;
11019: } else {
11020: my %crshash;
11021: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11022: if ($crshash{'internal.contentchange'} eq '') {
11023: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11024: if ($change eq '') {
11025: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11026: $change = $crshash{'internal.created'};
11027: }
11028: } else {
11029: $change = $crshash{'internal.contentchange'};
11030: }
11031: my $cachetime = 600;
11032: &do_cache_new('crschange',$hashid,$change,$cachetime);
11033: }
11034: return $change;
11035: }
11036:
11037: sub devalidate_coursechange_cache {
11038: my ($cnum,$cdom)=@_;
11039: my $hashid=$cnum.':'.$cdom;
11040: &devalidate_cache_new('crschange',$hashid);
11041: }
11042:
1.31 www 11043: # ------------------------------------------------- Update symbolic store links
11044:
11045: sub symblist {
11046: my ($mapname,%newhash)=@_;
1.438 www 11047: $mapname=&deversion(&declutter($mapname));
1.31 www 11048: my %hash;
1.620 albertel 11049: if (($env{'request.course.fn'}) && (%newhash)) {
11050: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11051: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11052: foreach my $url (keys(%newhash)) {
1.711 albertel 11053: next if ($url eq 'last_known'
11054: && $env{'form.no_update_last_known'});
11055: $hash{declutter($url)}=&encode_symb($mapname,
11056: $newhash{$url}->[1],
11057: $newhash{$url}->[0]);
1.191 harris41 11058: }
1.31 www 11059: if (untie(%hash)) {
11060: return 'ok';
11061: }
11062: }
11063: }
11064: return 'error';
1.212 www 11065: }
11066:
11067: # --------------------------------------------------------------- Verify a symb
11068:
11069: sub symbverify {
1.1172.2.11 raeburn 11070: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11071: my $thisfn=$thisurl;
1.439 www 11072: $thisfn=&declutter($thisfn);
1.215 www 11073: # direct jump to resource in page or to a sequence - will construct own symbs
11074: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11075: # check URL part
1.409 www 11076: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11077:
1.431 www 11078: unless ($url eq $thisfn) { return 0; }
1.213 www 11079:
1.216 www 11080: $symb=&symbclean($symb);
1.510 www 11081: $thisurl=&deversion($thisurl);
1.439 www 11082: $thisfn=&deversion($thisfn);
1.213 www 11083:
11084: my %bighash;
11085: my $okay=0;
1.431 www 11086:
1.620 albertel 11087: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11088: &GDBM_READER(),0640)) {
1.1172.2.13 raeburn 11089: my $noclutter;
1.1032 raeburn 11090: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11091: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 11092: if ($map =~ m{^uploaded/.+\.page$}) {
11093: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11094: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11095: $noclutter = 1;
11096: }
11097: }
11098: my $ids;
11099: if ($noclutter) {
11100: $ids=$bighash{'ids_'.$thisurl};
11101: } else {
11102: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11103: }
1.1102 raeburn 11104: unless ($ids) {
1.1172.2.13 raeburn 11105: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 11106: $ids=$bighash{$idkey};
1.216 www 11107: }
11108: if ($ids) {
11109: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 11110: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
11111: $symb =~ s/\?.+$//;
11112: }
1.800 albertel 11113: foreach my $id (split(/\,/,$ids)) {
11114: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11115: if (
11116: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 11117: eq $symb) {
1.1172.2.11 raeburn 11118: if (ref($encstate)) {
11119: $$encstate = $bighash{'encrypted_'.$id};
11120: }
1.1172.2.13 raeburn 11121: if (($env{'request.role.adv'}) ||
11122: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 11123: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 11124: $okay=1;
11125: last;
11126: }
11127: }
11128: }
1.216 www 11129: }
1.213 www 11130: untie(%bighash);
11131: }
11132: return $okay;
1.31 www 11133: }
11134:
1.210 www 11135: # --------------------------------------------------------------- Clean-up symb
11136:
11137: sub symbclean {
11138: my $symb=shift;
1.568 albertel 11139: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11140: # remove version from map
11141: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11142:
1.210 www 11143: # remove version from URL
11144: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11145:
1.507 www 11146: # remove wrapper
11147:
1.510 www 11148: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11149: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11150: return $symb;
1.409 www 11151: }
11152:
11153: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11154:
11155: sub encode_symb {
11156: my ($map,$resid,$url)=@_;
11157: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11158: }
1.409 www 11159:
11160: sub decode_symb {
1.568 albertel 11161: my $symb=shift;
11162: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11163: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11164: return (&fixversion($map),$resid,&fixversion($url));
11165: }
11166:
11167: sub fixversion {
11168: my $fn=shift;
1.609 banghart 11169: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11170: my %bighash;
11171: my $uri=&clutter($fn);
1.620 albertel 11172: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11173: # is this cached?
1.599 albertel 11174: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11175: if (defined($cached)) { return $result; }
11176: # unfortunately not cached, or expired
1.620 albertel 11177: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11178: &GDBM_READER(),0640)) {
11179: if ($bighash{'version_'.$uri}) {
11180: my $version=$bighash{'version_'.$uri};
1.444 www 11181: unless (($version eq 'mostrecent') ||
11182: ($version==&getversion($uri))) {
1.440 www 11183: $uri=~s/\.(\w+)$/\.$version\.$1/;
11184: }
11185: }
11186: untie %bighash;
1.413 www 11187: }
1.599 albertel 11188: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11189: }
11190:
11191: sub deversion {
11192: my $url=shift;
11193: $url=~s/\.\d+\.(\w+)$/\.$1/;
11194: return $url;
1.210 www 11195: }
11196:
1.31 www 11197: # ------------------------------------------------------ Return symb list entry
11198:
11199: sub symbread {
1.1172.2.66 raeburn 11200: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54 raeburn 11201: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66 raeburn 11202: if (defined($env{$cache_str})) {
11203: if ($ignorecachednull) {
11204: return $env{$cache_str} unless ($env{$cache_str} eq '');
11205: } else {
11206: return $env{$cache_str};
11207: }
11208: }
1.242 www 11209: # no filename provided? try from environment
1.1172.2.54 raeburn 11210: unless ($thisfn) {
1.620 albertel 11211: if ($env{'request.symb'}) {
1.1172.2.13 raeburn 11212: return $env{$cache_str}=&symbclean($env{'request.symb'});
11213: }
11214: $thisfn=$env{'request.filename'};
1.44 www 11215: }
1.569 albertel 11216: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11217: # is that filename actually a symb? Verify, clean, and return
11218: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11219: if (&symbverify($thisfn,$1)) {
1.620 albertel 11220: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11221: }
1.242 www 11222: }
1.44 www 11223: $thisfn=declutter($thisfn);
1.31 www 11224: my %hash;
1.37 www 11225: my %bighash;
11226: my $syval='';
1.620 albertel 11227: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11228: my $targetfn = $thisfn;
1.609 banghart 11229: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11230: $targetfn = 'adm/wrapper/'.$thisfn;
11231: }
1.687 albertel 11232: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11233: $targetfn=$1;
11234: }
1.620 albertel 11235: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11236: &GDBM_READER(),0640)) {
1.481 raeburn 11237: $syval=$hash{$targetfn};
1.37 www 11238: untie(%hash);
11239: }
11240: # ---------------------------------------------------------- There was an entry
11241: if ($syval) {
1.601 albertel 11242: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11243: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11244: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11245: #return $env{$cache_str}='';
1.601 albertel 11246: #}
11247: #$syval.=$1;
11248: #}
1.37 www 11249: } else {
11250: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11251: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11252: &GDBM_READER(),0640)) {
1.37 www 11253: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11254: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11255: unless ($ids) {
11256: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11257: }
11258: unless ($ids) {
11259: # alias?
11260: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11261: }
1.37 www 11262: if ($ids) {
11263: # ------------------------------------------------------------------- Has ID(s)
11264: my @possibilities=split(/\,/,$ids);
1.39 www 11265: if ($#possibilities==0) {
11266: # ----------------------------------------------- There is only one possibility
1.37 www 11267: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11268: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11269: $resid,$thisfn);
1.1172.2.66 raeburn 11270: if (ref($possibles) eq 'HASH') {
11271: $possibles->{$syval} = 1;
11272: }
11273: if ($checkforblock) {
11274: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11275: if (@blockers) {
11276: $syval = '';
11277: return;
11278: }
11279: }
11280: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11281: # ------------------------------------------ There is more than one possibility
11282: my $realpossible=0;
1.800 albertel 11283: foreach my $id (@possibilities) {
11284: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 11285: my $canaccess;
11286: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11287: $canaccess = 1;
11288: } else {
11289: $canaccess = &allowed('bre',$file);
11290: }
11291: if ($canaccess) {
11292: my ($mapid,$resid)=split(/\./,$id);
11293: if ($bighash{'map_type_'.$mapid} ne 'page') {
11294: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11295: $resid,$thisfn);
11296: if (ref($possibles) eq 'HASH') {
11297: $possibles->{$syval} = 1;
11298: }
11299: if ($checkforblock) {
11300: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11301: unless (@blockers > 0) {
11302: $syval = $poss_syval;
11303: $realpossible++;
11304: }
11305: } else {
11306: $syval = $poss_syval;
11307: $realpossible++;
11308: }
11309: }
1.39 www 11310: }
1.191 harris41 11311: }
1.39 www 11312: if ($realpossible!=1) { $syval=''; }
1.249 www 11313: } else {
11314: $syval='';
1.37 www 11315: }
11316: }
1.1172.2.66 raeburn 11317: untie(%bighash);
1.481 raeburn 11318: }
1.31 www 11319: }
1.62 www 11320: if ($syval) {
1.620 albertel 11321: return $env{$cache_str}=$syval;
1.62 www 11322: }
1.31 www 11323: }
1.949 raeburn 11324: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11325: return $env{$cache_str}='';
1.31 www 11326: }
11327:
11328: # ---------------------------------------------------------- Return random seed
11329:
1.32 www 11330: sub numval {
11331: my $txt=shift;
11332: $txt=~tr/A-J/0-9/;
11333: $txt=~tr/a-j/0-9/;
11334: $txt=~tr/K-T/0-9/;
11335: $txt=~tr/k-t/0-9/;
11336: $txt=~tr/U-Z/0-5/;
11337: $txt=~tr/u-z/0-5/;
11338: $txt=~s/\D//g;
1.564 albertel 11339: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11340: return int($txt);
1.368 albertel 11341: }
11342:
1.484 albertel 11343: sub numval2 {
11344: my $txt=shift;
11345: $txt=~tr/A-J/0-9/;
11346: $txt=~tr/a-j/0-9/;
11347: $txt=~tr/K-T/0-9/;
11348: $txt=~tr/k-t/0-9/;
11349: $txt=~tr/U-Z/0-5/;
11350: $txt=~tr/u-z/0-5/;
11351: $txt=~s/\D//g;
11352: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11353: my $total;
11354: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11355: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11356: return int($total);
11357: }
11358:
1.575 albertel 11359: sub numval3 {
11360: use integer;
11361: my $txt=shift;
11362: $txt=~tr/A-J/0-9/;
11363: $txt=~tr/a-j/0-9/;
11364: $txt=~tr/K-T/0-9/;
11365: $txt=~tr/k-t/0-9/;
11366: $txt=~tr/U-Z/0-5/;
11367: $txt=~tr/u-z/0-5/;
11368: $txt=~s/\D//g;
11369: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11370: my $total;
11371: foreach my $val (@txts) { $total+=$val; }
11372: if ($_64bit) { $total=(($total<<32)>>32); }
11373: return $total;
11374: }
11375:
1.675 albertel 11376: sub digest {
11377: my ($data)=@_;
11378: my $digest=&Digest::MD5::md5($data);
11379: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11380: my ($e,$f);
11381: {
11382: use integer;
11383: $e=($a+$b);
11384: $f=($c+$d);
11385: if ($_64bit) {
11386: $e=(($e<<32)>>32);
11387: $f=(($f<<32)>>32);
11388: }
11389: }
11390: if (wantarray) {
11391: return ($e,$f);
11392: } else {
11393: my $g;
11394: {
11395: use integer;
11396: $g=($e+$f);
11397: if ($_64bit) {
11398: $g=(($g<<32)>>32);
11399: }
11400: }
11401: return $g;
11402: }
11403: }
11404:
1.368 albertel 11405: sub latest_rnd_algorithm_id {
1.675 albertel 11406: return '64bit5';
1.366 albertel 11407: }
1.32 www 11408:
1.503 albertel 11409: sub get_rand_alg {
11410: my ($courseid)=@_;
1.790 albertel 11411: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11412: if ($courseid) {
1.620 albertel 11413: return $env{"course.$courseid.rndseed"};
1.503 albertel 11414: }
11415: return &latest_rnd_algorithm_id();
11416: }
11417:
1.562 albertel 11418: sub validCODE {
11419: my ($CODE)=@_;
11420: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11421: return 0;
11422: }
11423:
1.491 albertel 11424: sub getCODE {
1.620 albertel 11425: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11426: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11427: defined($Apache::lonhomework::parsing_a_task) ) &&
11428: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11429: return $Apache::lonhomework::history{'resource.CODE'};
11430: }
11431: return undef;
11432: }
1.1133 foxr 11433: #
11434: # Determines the random seed for a specific context:
11435: #
11436: # parameters:
11437: # symb - in course context the symb for the seed.
11438: # course_id - The course id of the form domain_coursenum.
11439: # domain - Domain for the user.
11440: # course - Course for the user.
11441: # cenv - environment of the course.
11442: #
11443: # NOTE:
11444: # All parameters are picked out of the environment if missing
11445: # or not defined.
11446: # If a symb cannot be determined the current time is used instead.
11447: #
11448: # For a given well defined symb, courside, domain, username,
11449: # and course environment, the seed is reproducible.
11450: #
1.31 www 11451: sub rndseed {
1.1133 foxr 11452: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11453: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11454: if (!defined($symb)) {
1.366 albertel 11455: unless ($symb=$wsymb) { return time; }
11456: }
1.1146 foxr 11457: if (!defined $courseid) {
11458: $courseid=$wcourseid;
11459: }
11460: if (!defined $domain) { $domain=$wdomain; }
11461: if (!defined $username) { $username=$wusername }
1.1133 foxr 11462:
11463: my $which;
11464: if (defined($cenv->{'rndseed'})) {
11465: $which = $cenv->{'rndseed'};
11466: } else {
11467: $which =&get_rand_alg($courseid);
11468: }
1.491 albertel 11469: if (defined(&getCODE())) {
1.675 albertel 11470: if ($which eq '64bit5') {
11471: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11472: } elsif ($which eq '64bit4') {
1.575 albertel 11473: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11474: } else {
11475: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11476: }
1.675 albertel 11477: } elsif ($which eq '64bit5') {
11478: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11479: } elsif ($which eq '64bit4') {
11480: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11481: } elsif ($which eq '64bit3') {
11482: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11483: } elsif ($which eq '64bit2') {
11484: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11485: } elsif ($which eq '64bit') {
11486: return &rndseed_64bit($symb,$courseid,$domain,$username);
11487: }
11488: return &rndseed_32bit($symb,$courseid,$domain,$username);
11489: }
11490:
11491: sub rndseed_32bit {
11492: my ($symb,$courseid,$domain,$username)=@_;
11493: {
11494: use integer;
11495: my $symbchck=unpack("%32C*",$symb) << 27;
11496: my $symbseed=numval($symb) << 22;
11497: my $namechck=unpack("%32C*",$username) << 17;
11498: my $nameseed=numval($username) << 12;
11499: my $domainseed=unpack("%32C*",$domain) << 7;
11500: my $courseseed=unpack("%32C*",$courseid);
11501: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11502: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11503: #&logthis("rndseed :$num:$symb");
1.564 albertel 11504: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11505: return $num;
11506: }
11507: }
11508:
11509: sub rndseed_64bit {
11510: my ($symb,$courseid,$domain,$username)=@_;
11511: {
11512: use integer;
11513: my $symbchck=unpack("%32S*",$symb) << 21;
11514: my $symbseed=numval($symb) << 10;
11515: my $namechck=unpack("%32S*",$username);
11516:
11517: my $nameseed=numval($username) << 21;
11518: my $domainseed=unpack("%32S*",$domain) << 10;
11519: my $courseseed=unpack("%32S*",$courseid);
11520:
11521: my $num1=$symbchck+$symbseed+$namechck;
11522: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11523: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11524: #&logthis("rndseed :$num:$symb");
1.564 albertel 11525: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11526: return "$num1,$num2";
1.155 albertel 11527: }
1.366 albertel 11528: }
11529:
1.443 albertel 11530: sub rndseed_64bit2 {
11531: my ($symb,$courseid,$domain,$username)=@_;
11532: {
11533: use integer;
11534: # strings need to be an even # of cahracters long, it it is odd the
11535: # last characters gets thrown away
11536: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11537: my $symbseed=numval($symb) << 10;
11538: my $namechck=unpack("%32S*",$username.' ');
11539:
11540: my $nameseed=numval($username) << 21;
1.501 albertel 11541: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11542: my $courseseed=unpack("%32S*",$courseid.' ');
11543:
11544: my $num1=$symbchck+$symbseed+$namechck;
11545: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11546: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11547: #&logthis("rndseed :$num:$symb");
1.803 albertel 11548: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11549: return "$num1,$num2";
11550: }
11551: }
11552:
11553: sub rndseed_64bit3 {
11554: my ($symb,$courseid,$domain,$username)=@_;
11555: {
11556: use integer;
11557: # strings need to be an even # of cahracters long, it it is odd the
11558: # last characters gets thrown away
11559: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11560: my $symbseed=numval2($symb) << 10;
11561: my $namechck=unpack("%32S*",$username.' ');
11562:
11563: my $nameseed=numval2($username) << 21;
1.443 albertel 11564: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11565: my $courseseed=unpack("%32S*",$courseid.' ');
11566:
11567: my $num1=$symbchck+$symbseed+$namechck;
11568: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11569: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11570: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11571: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11572:
1.503 albertel 11573: return "$num1:$num2";
1.443 albertel 11574: }
11575: }
11576:
1.575 albertel 11577: sub rndseed_64bit4 {
11578: my ($symb,$courseid,$domain,$username)=@_;
11579: {
11580: use integer;
11581: # strings need to be an even # of cahracters long, it it is odd the
11582: # last characters gets thrown away
11583: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11584: my $symbseed=numval3($symb) << 10;
11585: my $namechck=unpack("%32S*",$username.' ');
11586:
11587: my $nameseed=numval3($username) << 21;
11588: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11589: my $courseseed=unpack("%32S*",$courseid.' ');
11590:
11591: my $num1=$symbchck+$symbseed+$namechck;
11592: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11593: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11594: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11595: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11596:
1.575 albertel 11597: return "$num1:$num2";
11598: }
11599: }
11600:
1.675 albertel 11601: sub rndseed_64bit5 {
11602: my ($symb,$courseid,$domain,$username)=@_;
11603: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11604: return "$num1:$num2";
11605: }
11606:
1.366 albertel 11607: sub rndseed_CODE_64bit {
11608: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11609: {
1.366 albertel 11610: use integer;
1.443 albertel 11611: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11612: my $symbseed=numval2($symb);
1.491 albertel 11613: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11614: my $CODEseed=numval(&getCODE());
1.443 albertel 11615: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11616: my $num1=$symbseed+$CODEchck;
11617: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11618: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11619: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11620: if ($_64bit) { $num1=(($num1<<32)>>32); }
11621: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11622: return "$num1:$num2";
1.366 albertel 11623: }
11624: }
11625:
1.575 albertel 11626: sub rndseed_CODE_64bit4 {
11627: my ($symb,$courseid,$domain,$username)=@_;
11628: {
11629: use integer;
11630: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11631: my $symbseed=numval3($symb);
11632: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11633: my $CODEseed=numval3(&getCODE());
11634: my $courseseed=unpack("%32S*",$courseid.' ');
11635: my $num1=$symbseed+$CODEchck;
11636: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11637: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11638: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11639: if ($_64bit) { $num1=(($num1<<32)>>32); }
11640: if ($_64bit) { $num2=(($num2<<32)>>32); }
11641: return "$num1:$num2";
11642: }
11643: }
11644:
1.675 albertel 11645: sub rndseed_CODE_64bit5 {
11646: my ($symb,$courseid,$domain,$username)=@_;
11647: my $code = &getCODE();
11648: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11649: return "$num1:$num2";
11650: }
11651:
1.366 albertel 11652: sub setup_random_from_rndseed {
11653: my ($rndseed)=@_;
1.503 albertel 11654: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 11655: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11656: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11657: &Math::Random::random_set_seed_from_phrase($rndseed);
11658: } else {
11659: &Math::Random::random_set_seed($num1,$num2);
11660: }
1.366 albertel 11661: } else {
11662: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11663: }
1.36 albertel 11664: }
11665:
1.474 albertel 11666: sub latest_receipt_algorithm_id {
1.835 albertel 11667: return 'receipt3';
1.474 albertel 11668: }
11669:
1.480 www 11670: sub recunique {
11671: my $fucourseid=shift;
11672: my $unique;
1.835 albertel 11673: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11674: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11675: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11676: } else {
11677: $unique=$perlvar{'lonReceipt'};
11678: }
11679: return unpack("%32C*",$unique);
11680: }
11681:
11682: sub recprefix {
11683: my $fucourseid=shift;
11684: my $prefix;
1.835 albertel 11685: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11686: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11687: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11688: } else {
11689: $prefix=$perlvar{'lonHostID'};
11690: }
11691: return unpack("%32C*",$prefix);
11692: }
11693:
1.76 www 11694: sub ireceipt {
1.474 albertel 11695: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11696:
11697: my $return =&recprefix($fucourseid).'-';
11698:
11699: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11700: $env{'request.state'} eq 'construct') {
11701: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11702: return $return;
11703: }
11704:
1.76 www 11705: my $cuname=unpack("%32C*",$funame);
11706: my $cudom=unpack("%32C*",$fudom);
11707: my $cucourseid=unpack("%32C*",$fucourseid);
11708: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11709: my $cunique=&recunique($fucourseid);
1.474 albertel 11710: my $cpart=unpack("%32S*",$part);
1.835 albertel 11711: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11712:
1.790 albertel 11713: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11714:
11715: $return.= ($cunique%$cuname+
11716: $cunique%$cudom+
11717: $cusymb%$cuname+
11718: $cusymb%$cudom+
11719: $cucourseid%$cuname+
11720: $cucourseid%$cudom+
11721: $cpart%$cuname+
11722: $cpart%$cudom);
11723: } else {
11724: $return.= ($cunique%$cuname+
11725: $cunique%$cudom+
11726: $cusymb%$cuname+
11727: $cusymb%$cudom+
11728: $cucourseid%$cuname+
11729: $cucourseid%$cudom);
11730: }
11731: return $return;
1.76 www 11732: }
11733:
11734: sub receipt {
1.474 albertel 11735: my ($part)=@_;
1.790 albertel 11736: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11737: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11738: }
1.260 ng 11739:
1.790 albertel 11740: sub whichuser {
11741: my ($passedsymb)=@_;
11742: my ($symb,$courseid,$domain,$name,$publicuser);
11743: if (defined($env{'form.grade_symb'})) {
11744: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11745: my $allowed=&allowed('vgr',$tmp_courseid);
11746: if (!$allowed &&
11747: exists($env{'request.course.sec'}) &&
11748: $env{'request.course.sec'} !~ /^\s*$/) {
11749: $allowed=&allowed('vgr',$tmp_courseid.
11750: '/'.$env{'request.course.sec'});
11751: }
11752: if ($allowed) {
11753: ($symb)=&get_env_multiple('form.grade_symb');
11754: $courseid=$tmp_courseid;
11755: ($domain)=&get_env_multiple('form.grade_domain');
11756: ($name)=&get_env_multiple('form.grade_username');
11757: return ($symb,$courseid,$domain,$name,$publicuser);
11758: }
11759: }
11760: if (!$passedsymb) {
11761: $symb=&symbread();
11762: } else {
11763: $symb=$passedsymb;
11764: }
11765: $courseid=$env{'request.course.id'};
11766: $domain=$env{'user.domain'};
11767: $name=$env{'user.name'};
11768: if ($name eq 'public' && $domain eq 'public') {
11769: if (!defined($env{'form.username'})) {
11770: $env{'form.username'}.=time.rand(10000000);
11771: }
11772: $name.=$env{'form.username'};
11773: }
11774: return ($symb,$courseid,$domain,$name,$publicuser);
11775:
11776: }
11777:
1.36 albertel 11778: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11779: # returns either the contents of the file or
11780: # -1 if the file doesn't exist
1.481 raeburn 11781: #
11782: # if the target is a file that was uploaded via DOCS,
11783: # a check will be made to see if a current copy exists on the local server,
11784: # if it does this will be served, otherwise a copy will be retrieved from
11785: # the home server for the course and stored in /home/httpd/html/userfiles on
11786: # the local server.
1.472 albertel 11787:
1.36 albertel 11788: sub getfile {
1.538 albertel 11789: my ($file) = @_;
1.609 banghart 11790: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11791: &repcopy($file);
11792: return &readfile($file);
11793: }
11794:
11795: sub repcopy_userfile {
11796: my ($file)=@_;
1.1142 raeburn 11797: my $londocroot = $perlvar{'lonDocRoot'};
11798: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11799: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11800: my ($cdom,$cnum,$filename) =
1.811 albertel 11801: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11802: my $uri="/uploaded/$cdom/$cnum/$filename";
11803: if (-e "$file") {
1.828 www 11804: # we already have a local copy, check it out
1.538 albertel 11805: my @fileinfo = stat($file);
1.828 www 11806: my $rtncode;
11807: my $info;
1.538 albertel 11808: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11809: if ($lwpresp ne 'ok') {
1.828 www 11810: # there is no such file anymore, even though we had a local copy
1.482 albertel 11811: if ($rtncode eq '404') {
1.538 albertel 11812: unlink($file);
1.482 albertel 11813: }
11814: return -1;
11815: }
11816: if ($info < $fileinfo[9]) {
1.828 www 11817: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11818: return 'ok';
1.828 www 11819: } else {
11820: # the file is outdated, get rid of it
11821: unlink($file);
1.482 albertel 11822: }
1.828 www 11823: }
11824: # one way or the other, at this point, we don't have the file
11825: # construct the correct path for the file
11826: my @parts = ($cdom,$cnum);
11827: if ($filename =~ m|^(.+)/[^/]+$|) {
11828: push @parts, split(/\//,$1);
11829: }
11830: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11831: foreach my $part (@parts) {
11832: $path .= '/'.$part;
11833: if (!-e $path) {
11834: mkdir($path,0770);
1.482 albertel 11835: }
11836: }
1.828 www 11837: # now the path exists for sure
11838: # get a user agent
11839: my $ua=new LWP::UserAgent;
11840: my $transferfile=$file.'.in.transfer';
11841: # FIXME: this should flock
11842: if (-e $transferfile) { return 'ok'; }
11843: my $request;
11844: $uri=~s/^\///;
1.980 raeburn 11845: my $homeserver = &homeserver($cnum,$cdom);
11846: my $protocol = $protocol{$homeserver};
11847: $protocol = 'http' if ($protocol ne 'https');
11848: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11849: my $response=$ua->request($request,$transferfile);
11850: # did it work?
11851: if ($response->is_error()) {
11852: unlink($transferfile);
11853: &logthis("Userfile repcopy failed for $uri");
11854: return -1;
11855: }
11856: # worked, rename the transfer file
11857: rename($transferfile,$file);
1.607 raeburn 11858: return 'ok';
1.481 raeburn 11859: }
11860:
1.517 albertel 11861: sub tokenwrapper {
11862: my $uri=shift;
1.980 raeburn 11863: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11864: $uri=~s|^/||;
1.620 albertel 11865: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11866: my $token=$1;
1.552 albertel 11867: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11868: if ($udom && $uname && $file) {
11869: $file=~s|(\?\.*)*$||;
1.949 raeburn 11870: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11871: my $homeserver = &homeserver($uname,$udom);
11872: my $protocol = $protocol{$homeserver};
11873: $protocol = 'http' if ($protocol ne 'https');
11874: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11875: (($uri=~/\?/)?'&':'?').'token='.$token.
11876: '&tokenissued='.$perlvar{'lonHostID'};
11877: } else {
11878: return '/adm/notfound.html';
11879: }
11880: }
11881:
1.828 www 11882: # call with reqtype HEAD: get last modification time
11883: # call with reqtype GET: get the file contents
11884: # Do not call this with reqtype GET for large files! It loads everything into memory
11885: #
1.481 raeburn 11886: sub getuploaded {
11887: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11888: $uri=~s/^\///;
1.980 raeburn 11889: my $homeserver = &homeserver($cnum,$cdom);
11890: my $protocol = $protocol{$homeserver};
11891: $protocol = 'http' if ($protocol ne 'https');
11892: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11893: my $ua=new LWP::UserAgent;
11894: my $request=new HTTP::Request($reqtype,$uri);
11895: my $response=$ua->request($request);
11896: $$rtncode = $response->code;
1.482 albertel 11897: if (! $response->is_success()) {
11898: return 'failed';
11899: }
11900: if ($reqtype eq 'HEAD') {
1.486 www 11901: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11902: } elsif ($reqtype eq 'GET') {
11903: $$info = $response->content;
1.472 albertel 11904: }
1.482 albertel 11905: return 'ok';
1.36 albertel 11906: }
11907:
1.481 raeburn 11908: sub readfile {
11909: my $file = shift;
11910: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11911: my $fh;
11912: open($fh,"<$file");
11913: my $a='';
1.800 albertel 11914: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11915: return $a;
11916: }
11917:
1.36 albertel 11918: sub filelocation {
1.590 banghart 11919: my ($dir,$file) = @_;
11920: my $location;
11921: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11922:
11923: if ($file =~ m-^/adm/-) {
11924: $file=~s-^/adm/wrapper/-/-;
11925: $file=~s-^/adm/coursedocs/showdoc/-/-;
11926: }
1.882 albertel 11927:
1.1139 www 11928: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11929: $location = $file;
1.609 banghart 11930: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11931: my ($udom,$uname,$filename)=
1.811 albertel 11932: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11933: my $home=&homeserver($uname,$udom);
11934: my $is_me=0;
11935: my @ids=¤t_machine_ids();
11936: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11937: if ($is_me) {
1.1117 foxr 11938: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11939: } else {
11940: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11941: $udom.'/'.$uname.'/'.$filename;
11942: }
1.882 albertel 11943: } elsif ($file =~ m-^/adm/-) {
11944: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11945: } else {
11946: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11947: $file=~s:^/(res|priv)/:/:;
11948: my $space=$1;
1.590 banghart 11949: if ( !( $file =~ m:^/:) ) {
11950: $location = $dir. '/'.$file;
11951: } else {
1.1142 raeburn 11952: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11953: }
1.59 albertel 11954: }
1.590 banghart 11955: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11956: while ($location=~m{/\.\./}) {
11957: if ($location =~ m{/[^/]+/\.\./}) {
11958: $location=~ s{/[^/]+/\.\./}{/}g;
11959: } else {
11960: $location=~ s{/\.\./}{/}g;
11961: }
11962: } #remove dir/..
1.590 banghart 11963: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11964: return $location;
1.46 www 11965: }
1.36 albertel 11966:
1.46 www 11967: sub hreflocation {
11968: my ($dir,$file)=@_;
1.980 raeburn 11969: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11970: $file=filelocation($dir,$file);
1.700 albertel 11971: } elsif ($file=~m-^/adm/-) {
11972: $file=~s-^/adm/wrapper/-/-;
11973: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11974: }
11975: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11976: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11977: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11978: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11979: {/uploaded/$1/$2/}x;
1.46 www 11980: }
1.913 albertel 11981: if ($file=~ m{^/userfiles/}) {
11982: $file =~ s{^/userfiles/}{/uploaded/};
11983: }
1.462 albertel 11984: return $file;
1.465 albertel 11985: }
11986:
1.1139 www 11987:
11988:
11989:
11990:
1.465 albertel 11991: sub current_machine_domains {
1.853 albertel 11992: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11993: }
11994:
11995: sub machine_domains {
11996: my ($hostname) = @_;
1.465 albertel 11997: my @domains;
1.838 albertel 11998: my %hostname = &all_hostnames();
1.465 albertel 11999: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12000: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12001: if ($hostname eq $name) {
1.844 albertel 12002: push(@domains,&host_domain($id));
1.465 albertel 12003: }
12004: }
12005: return @domains;
12006: }
12007:
12008: sub current_machine_ids {
1.853 albertel 12009: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12010: }
12011:
12012: sub machine_ids {
12013: my ($hostname) = @_;
12014: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12015: my @ids;
1.888 albertel 12016: my %name_to_host = &all_names();
1.889 albertel 12017: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12018: return @{ $name_to_host{$hostname} };
12019: }
12020: return;
1.31 www 12021: }
12022:
1.824 raeburn 12023: sub additional_machine_domains {
12024: my @domains;
12025: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12026: while( my $line = <$fh>) {
12027: $line =~ s/\s//g;
12028: push(@domains,$line);
12029: }
12030: return @domains;
12031: }
12032:
12033: sub default_login_domain {
12034: my $domain = $perlvar{'lonDefDomain'};
12035: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12036: foreach my $posdom (¤t_machine_domains(),
12037: &additional_machine_domains()) {
12038: if (lc($posdom) eq lc($testdomain)) {
12039: $domain=$posdom;
12040: last;
12041: }
12042: }
12043: return $domain;
12044: }
12045:
1.31 www 12046: # ------------------------------------------------------------- Declutters URLs
12047:
12048: sub declutter {
12049: my $thisfn=shift;
1.569 albertel 12050: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 12051: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12052: $thisfn=~s{^/home/httpd/html}{};
12053: }
1.31 www 12054: $thisfn=~s/^\///;
1.697 albertel 12055: $thisfn=~s|^adm/wrapper/||;
12056: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12057: $thisfn=~s/^res\///;
1.1172 bisitz 12058: $thisfn=~s/^priv\///;
1.1032 raeburn 12059: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12060: $thisfn=~s/\?.+$//;
12061: }
1.268 www 12062: return $thisfn;
12063: }
12064:
12065: # ------------------------------------------------------------- Clutter up URLs
12066:
12067: sub clutter {
12068: my $thisfn='/'.&declutter(shift);
1.887 albertel 12069: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12070: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12071: $thisfn='/res'.$thisfn;
12072: }
1.1031 raeburn 12073: if ($thisfn !~m|^/adm|) {
12074: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12075: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12076: } else {
12077: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12078: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12079: if ($embstyle eq 'ssi'
12080: || ($embstyle eq 'hdn')
12081: || ($embstyle eq 'rat')
12082: || ($embstyle eq 'prv')
12083: || ($embstyle eq 'ign')) {
12084: #do nothing with these
12085: } elsif (($embstyle eq 'img')
1.695 albertel 12086: || ($embstyle eq 'emb')
12087: || ($embstyle eq 'wrp')) {
12088: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12089: } elsif ($embstyle eq 'unk'
12090: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12091: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12092: } else {
1.718 www 12093: # &logthis("Got a blank emb style");
1.695 albertel 12094: }
1.694 albertel 12095: }
12096: }
1.31 www 12097: return $thisfn;
1.12 www 12098: }
12099:
1.787 albertel 12100: sub clutter_with_no_wrapper {
12101: my $uri = &clutter(shift);
12102: if ($uri =~ m-^/adm/-) {
12103: $uri =~ s-^/adm/wrapper/-/-;
12104: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12105: }
12106: return $uri;
12107: }
12108:
1.557 albertel 12109: sub freeze_escape {
12110: my ($value)=@_;
12111: if (ref($value)) {
12112: $value=&nfreeze($value);
12113: return '__FROZEN__'.&escape($value);
12114: }
12115: return &escape($value);
12116: }
12117:
1.11 www 12118:
1.557 albertel 12119: sub thaw_unescape {
12120: my ($value)=@_;
12121: if ($value =~ /^__FROZEN__/) {
12122: substr($value,0,10,undef);
12123: $value=&unescape($value);
12124: return &thaw($value);
12125: }
12126: return &unescape($value);
12127: }
12128:
1.436 albertel 12129: sub correct_line_ends {
12130: my ($result)=@_;
12131: $$result =~s/\r\n/\n/mg;
12132: $$result =~s/\r/\n/mg;
1.415 albertel 12133: }
1.1 albertel 12134: # ================================================================ Main Program
12135:
1.184 www 12136: sub goodbye {
1.204 albertel 12137: &logthis("Starting Shut down");
1.443 albertel 12138: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12139: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12140: #converted
1.599 albertel 12141: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12142: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12143: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12144: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12145: #1.1 only
1.870 albertel 12146: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12147: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12148: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12149: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12150: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12151: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12152: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12153: &flushcourselogs();
12154: &logthis("Shutting down");
12155: }
12156:
1.852 albertel 12157: sub get_dns {
1.1172.2.17 raeburn 12158: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12159: if (!$ignore_cache) {
12160: my ($content,$cached)=
12161: &Apache::lonnet::is_cached_new('dns',$url);
12162: if ($cached) {
1.1172.2.17 raeburn 12163: &$func($content,$hashref);
1.869 albertel 12164: return;
12165: }
12166: }
12167:
12168: my %alldns;
1.852 albertel 12169: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12170: foreach my $dns (<$config>) {
12171: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12172: my $line = $1;
12173: my ($host,$protocol) = split(/:/,$line);
12174: if ($protocol ne 'https') {
12175: $protocol = 'http';
12176: }
12177: $alldns{$host} = $protocol;
1.869 albertel 12178: }
12179: while (%alldns) {
1.1172.2.52 raeburn 12180: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12181: my $ua=new LWP::UserAgent;
1.1134 raeburn 12182: $ua->timeout(30);
1.979 raeburn 12183: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12184: my $response=$ua->request($request);
1.979 raeburn 12185: delete($alldns{$dns});
1.852 albertel 12186: next if ($response->is_error());
12187: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 12188: unless ($nocache) {
1.1172.2.23 raeburn 12189: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 12190: }
12191: &$func(\@content,$hashref);
1.869 albertel 12192: return;
1.852 albertel 12193: }
12194: close($config);
1.871 albertel 12195: my $which = (split('/',$url))[3];
12196: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12197: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12198: my @content = <$config>;
1.1172.2.17 raeburn 12199: &$func(\@content,$hashref);
12200: return;
12201: }
12202:
12203: # ------------------------------------------------------Get DNS checksums file
12204: sub parse_dns_checksums_tab {
12205: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 12206: my $lonhost = $perlvar{'lonHostID'};
12207: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 12208: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 12209: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12210: my $webconfdir = '/etc/httpd/conf';
12211: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12212: $webconfdir = '/etc/apache2';
12213: } elsif ($distro =~ /^sles(\d+)$/) {
12214: if ($1 >= 10) {
12215: $webconfdir = '/etc/apache2';
12216: }
12217: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12218: if ($1 >= 10.0) {
12219: $webconfdir = '/etc/apache2';
12220: }
12221: }
1.1172.2.17 raeburn 12222: my ($release,$timestamp) = split(/\-/,$loncaparev);
12223: my (%chksum,%revnum);
12224: if (ref($lines) eq 'ARRAY') {
12225: chomp(@{$lines});
1.1172.2.34 raeburn 12226: my $version = shift(@{$lines});
12227: if ($version eq $release) {
1.1172.2.17 raeburn 12228: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 12229: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 12230: if ($file =~ m{^/etc/httpd/conf}) {
12231: if ($webconfdir eq '/etc/apache2') {
12232: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12233: }
12234: }
1.1172.2.34 raeburn 12235: $chksum{$file} = $shasum;
12236: $revnum{$file} = $version;
1.1172.2.17 raeburn 12237: }
12238: if (ref($hashref) eq 'HASH') {
12239: %{$hashref} = (
12240: sums => \%chksum,
12241: versions => \%revnum,
12242: );
12243: }
12244: }
12245: }
1.869 albertel 12246: return;
1.852 albertel 12247: }
1.1172.2.17 raeburn 12248:
12249: sub fetch_dns_checksums {
12250: my %checksums;
1.1172.2.34 raeburn 12251: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 12252: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 12253: my ($release,$timestamp) = split(/\-/,$loncaparev);
12254: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 12255: \%checksums);
12256: return \%checksums;
12257: }
12258:
1.327 albertel 12259: # ------------------------------------------------------------ Read domain file
12260: {
1.852 albertel 12261: my $loaded;
1.846 albertel 12262: my %domain;
12263:
1.852 albertel 12264: sub parse_domain_tab {
12265: my ($lines) = @_;
12266: foreach my $line (@$lines) {
12267: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12268:
1.846 albertel 12269: chomp($line);
1.852 albertel 12270: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12271: my %this_domain;
12272: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12273: 'lang_def', 'city', 'longi', 'lati',
12274: 'primary') {
12275: $this_domain{$field} = shift(@elements);
12276: }
12277: $domain{$name} = \%this_domain;
1.852 albertel 12278: }
12279: }
1.864 albertel 12280:
12281: sub reset_domain_info {
12282: undef($loaded);
12283: undef(%domain);
12284: }
12285:
1.852 albertel 12286: sub load_domain_tab {
1.1172.2.70! raeburn 12287: my ($ignore_cache,$nocache) = @_;
! 12288: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 12289: my $fh;
12290: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12291: my @lines = <$fh>;
12292: &parse_domain_tab(\@lines);
1.448 albertel 12293: }
1.852 albertel 12294: close($fh);
12295: $loaded = 1;
1.327 albertel 12296: }
1.846 albertel 12297:
12298: sub domain {
1.852 albertel 12299: &load_domain_tab() if (!$loaded);
12300:
1.846 albertel 12301: my ($name,$what) = @_;
12302: return if ( !exists($domain{$name}) );
12303:
12304: if (!$what) {
12305: return $domain{$name}{'description'};
12306: }
12307: return $domain{$name}{$what};
12308: }
1.974 raeburn 12309:
12310: sub domain_info {
12311: &load_domain_tab() if (!$loaded);
12312: return %domain;
12313: }
12314:
1.327 albertel 12315: }
12316:
12317:
1.1 albertel 12318: # ------------------------------------------------------------- Read hosts file
12319: {
1.838 albertel 12320: my %hostname;
1.844 albertel 12321: my %hostdom;
1.845 albertel 12322: my %libserv;
1.852 albertel 12323: my $loaded;
1.888 albertel 12324: my %name_to_host;
1.1074 raeburn 12325: my %internetdom;
1.1107 raeburn 12326: my %LC_dns_serv;
1.852 albertel 12327:
12328: sub parse_hosts_tab {
12329: my ($file) = @_;
12330: foreach my $configline (@$file) {
12331: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12332: chomp($configline);
12333: if ($configline =~ /^\^/) {
12334: if ($configline =~ /^\^([\w.\-]+)/) {
12335: $LC_dns_serv{$1} = 1;
12336: }
12337: next;
12338: }
1.1074 raeburn 12339: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12340: $name=~s/\s//g;
12341: if ($id && $domain && $role && $name) {
12342: $hostname{$id}=$name;
1.888 albertel 12343: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12344: $hostdom{$id}=$domain;
12345: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12346: if (defined($protocol)) {
12347: if ($protocol eq 'https') {
12348: $protocol{$id} = $protocol;
12349: } else {
12350: $protocol{$id} = 'http';
12351: }
1.968 raeburn 12352: } else {
1.969 raeburn 12353: $protocol{$id} = 'http';
1.968 raeburn 12354: }
1.1074 raeburn 12355: if (defined($intdom)) {
12356: $internetdom{$id} = $intdom;
12357: }
1.852 albertel 12358: }
12359: }
12360: }
1.864 albertel 12361:
12362: sub reset_hosts_info {
1.897 albertel 12363: &purge_remembered();
1.864 albertel 12364: &reset_domain_info();
12365: &reset_hosts_ip_info();
1.892 albertel 12366: undef(%name_to_host);
1.864 albertel 12367: undef(%hostname);
12368: undef(%hostdom);
12369: undef(%libserv);
12370: undef($loaded);
12371: }
1.1 albertel 12372:
1.852 albertel 12373: sub load_hosts_tab {
1.1172.2.70! raeburn 12374: my ($ignore_cache,$nocache) = @_;
! 12375: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852 albertel 12376: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12377: my @config = <$config>;
12378: &parse_hosts_tab(\@config);
12379: close($config);
12380: $loaded=1;
1.1 albertel 12381: }
1.852 albertel 12382:
1.838 albertel 12383: sub hostname {
1.852 albertel 12384: &load_hosts_tab() if (!$loaded);
12385:
1.838 albertel 12386: my ($lonid) = @_;
12387: return $hostname{$lonid};
12388: }
1.845 albertel 12389:
1.838 albertel 12390: sub all_hostnames {
1.852 albertel 12391: &load_hosts_tab() if (!$loaded);
12392:
1.838 albertel 12393: return %hostname;
12394: }
1.845 albertel 12395:
1.888 albertel 12396: sub all_names {
1.1172.2.70! raeburn 12397: my ($ignore_cache,$nocache) = @_;
! 12398: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 12399:
12400: return %name_to_host;
12401: }
12402:
1.974 raeburn 12403: sub all_host_domain {
12404: &load_hosts_tab() if (!$loaded);
12405: return %hostdom;
12406: }
12407:
1.845 albertel 12408: sub is_library {
1.852 albertel 12409: &load_hosts_tab() if (!$loaded);
12410:
1.845 albertel 12411: return exists($libserv{$_[0]});
12412: }
12413:
12414: sub all_library {
1.852 albertel 12415: &load_hosts_tab() if (!$loaded);
12416:
1.845 albertel 12417: return %libserv;
12418: }
12419:
1.1062 droeschl 12420: sub unique_library {
12421: #2x reverse removes all hostnames that appear more than once
12422: my %unique = reverse &all_library();
12423: return reverse %unique;
12424: }
12425:
1.841 albertel 12426: sub get_servers {
1.852 albertel 12427: &load_hosts_tab() if (!$loaded);
12428:
1.841 albertel 12429: my ($domain,$type) = @_;
12430: my %possible_hosts = ($type eq 'library') ? %libserv
12431: : %hostname;
12432: my %result;
1.842 albertel 12433: if (ref($domain) eq 'ARRAY') {
12434: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12435: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12436: $result{$host} = $hostname;
12437: }
12438: }
12439: } else {
12440: while ( my ($host,$hostname) = each(%possible_hosts)) {
12441: if ($hostdom{$host} eq $domain) {
12442: $result{$host} = $hostname;
12443: }
1.841 albertel 12444: }
12445: }
12446: return %result;
12447: }
1.845 albertel 12448:
1.1062 droeschl 12449: sub get_unique_servers {
12450: my %unique = reverse &get_servers(@_);
12451: return reverse %unique;
12452: }
12453:
1.844 albertel 12454: sub host_domain {
1.852 albertel 12455: &load_hosts_tab() if (!$loaded);
12456:
1.844 albertel 12457: my ($lonid) = @_;
12458: return $hostdom{$lonid};
12459: }
12460:
1.841 albertel 12461: sub all_domains {
1.852 albertel 12462: &load_hosts_tab() if (!$loaded);
12463:
1.841 albertel 12464: my %seen;
12465: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12466: return @uniq;
12467: }
1.1074 raeburn 12468:
12469: sub internet_dom {
12470: &load_hosts_tab() if (!$loaded);
12471:
12472: my ($lonid) = @_;
12473: return $internetdom{$lonid};
12474: }
1.1107 raeburn 12475:
12476: sub is_LC_dns {
12477: &load_hosts_tab() if (!$loaded);
12478:
12479: my ($hostname) = @_;
12480: return exists($LC_dns_serv{$hostname});
12481: }
12482:
1.1 albertel 12483: }
12484:
1.847 albertel 12485: {
12486: my %iphost;
1.856 albertel 12487: my %name_to_ip;
12488: my %lonid_to_ip;
1.869 albertel 12489:
1.847 albertel 12490: sub get_hosts_from_ip {
12491: my ($ip) = @_;
12492: my %iphosts = &get_iphost();
12493: if (ref($iphosts{$ip})) {
12494: return @{$iphosts{$ip}};
12495: }
12496: return;
1.839 albertel 12497: }
1.864 albertel 12498:
12499: sub reset_hosts_ip_info {
12500: undef(%iphost);
12501: undef(%name_to_ip);
12502: undef(%lonid_to_ip);
12503: }
1.856 albertel 12504:
12505: sub get_host_ip {
12506: my ($lonid) = @_;
12507: if (exists($lonid_to_ip{$lonid})) {
12508: return $lonid_to_ip{$lonid};
12509: }
12510: my $name=&hostname($lonid);
12511: my $ip = gethostbyname($name);
12512: return if (!$ip || length($ip) ne 4);
12513: $ip=inet_ntoa($ip);
12514: $name_to_ip{$name} = $ip;
12515: $lonid_to_ip{$lonid} = $ip;
12516: return $ip;
12517: }
1.847 albertel 12518:
12519: sub get_iphost {
1.1172.2.70! raeburn 12520: my ($ignore_cache,$nocache) = @_;
1.894 albertel 12521:
1.869 albertel 12522: if (!$ignore_cache) {
12523: if (%iphost) {
12524: return %iphost;
12525: }
12526: my ($ip_info,$cached)=
12527: &Apache::lonnet::is_cached_new('iphost','iphost');
12528: if ($cached) {
12529: %iphost = %{$ip_info->[0]};
12530: %name_to_ip = %{$ip_info->[1]};
12531: %lonid_to_ip = %{$ip_info->[2]};
12532: return %iphost;
12533: }
12534: }
1.894 albertel 12535:
12536: # get yesterday's info for fallback
12537: my %old_name_to_ip;
12538: my ($ip_info,$cached)=
12539: &Apache::lonnet::is_cached_new('iphost','iphost');
12540: if ($cached) {
12541: %old_name_to_ip = %{$ip_info->[1]};
12542: }
12543:
1.1172.2.70! raeburn 12544: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 12545: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12546: my $ip;
12547: if (!exists($name_to_ip{$name})) {
12548: $ip = gethostbyname($name);
12549: if (!$ip || length($ip) ne 4) {
1.894 albertel 12550: if (defined($old_name_to_ip{$name})) {
12551: $ip = $old_name_to_ip{$name};
12552: &logthis("Can't find $name defaulting to old $ip");
12553: } else {
12554: &logthis("Name $name no IP found");
12555: next;
12556: }
12557: } else {
12558: $ip=inet_ntoa($ip);
1.847 albertel 12559: }
12560: $name_to_ip{$name} = $ip;
12561: } else {
12562: $ip = $name_to_ip{$name};
1.653 albertel 12563: }
1.888 albertel 12564: foreach my $id (@{ $name_to_host{$name} }) {
12565: $lonid_to_ip{$id} = $ip;
12566: }
12567: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12568: }
1.1172.2.70! raeburn 12569: unless ($nocache) {
! 12570: &do_cache_new('iphost','iphost',
! 12571: [\%iphost,\%name_to_ip,\%lonid_to_ip],
! 12572: 48*60*60);
! 12573: }
1.869 albertel 12574:
1.847 albertel 12575: return %iphost;
1.598 albertel 12576: }
12577:
1.992 raeburn 12578: #
12579: # Given a DNS returns the loncapa host name for that DNS
12580: #
12581: sub host_from_dns {
12582: my ($dns) = @_;
12583: my @hosts;
12584: my $ip;
12585:
1.993 raeburn 12586: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12587: $ip = $name_to_ip{$dns};
12588: }
12589: if (!$ip) {
12590: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12591: if (length($ip) == 4) {
12592: $ip = &IO::Socket::inet_ntoa($ip);
12593: }
12594: }
12595: if ($ip) {
12596: @hosts = get_hosts_from_ip($ip);
12597: return $hosts[0];
12598: }
12599: return undef;
1.986 foxr 12600: }
1.992 raeburn 12601:
1.1074 raeburn 12602: sub get_internet_names {
12603: my ($lonid) = @_;
12604: return if ($lonid eq '');
12605: my ($idnref,$cached)=
12606: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12607: if ($cached) {
12608: return $idnref;
12609: }
12610: my $ip = &get_host_ip($lonid);
12611: my @hosts = &get_hosts_from_ip($ip);
12612: my %iphost = &get_iphost();
12613: my (@idns,%seen);
12614: foreach my $id (@hosts) {
12615: my $dom = &host_domain($id);
12616: my $prim_id = &domain($dom,'primary');
12617: my $prim_ip = &get_host_ip($prim_id);
12618: next if ($seen{$prim_ip});
12619: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12620: foreach my $id (@{$iphost{$prim_ip}}) {
12621: my $intdom = &internet_dom($id);
12622: unless (grep(/^\Q$intdom\E$/,@idns)) {
12623: push(@idns,$intdom);
12624: }
12625: }
12626: }
12627: $seen{$prim_ip} = 1;
12628: }
1.1172.2.23 raeburn 12629: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12630: }
12631:
1.986 foxr 12632: }
12633:
1.1079 raeburn 12634: sub all_loncaparevs {
1.1172.2.39 raeburn 12635: 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 12636: }
12637:
1.1172.2.27 raeburn 12638: # ------------------------------------------------------- Read loncaparev table
12639: {
12640: sub load_loncaparevs {
12641: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12642: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12643: while (my $configline=<$config>) {
12644: chomp($configline);
12645: my ($hostid,$loncaparev)=split(/:/,$configline);
12646: $loncaparevs{$hostid}=$loncaparev;
12647: }
12648: close($config);
12649: }
12650: }
12651: }
12652: }
12653:
12654: # ----------------------------------------------------- Read serverhostID table
12655: {
12656: sub load_serverhomeIDs {
12657: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12658: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12659: while (my $configline=<$config>) {
12660: chomp($configline);
12661: my ($name,$id)=split(/:/,$configline);
12662: $serverhomeIDs{$name}=$id;
12663: }
12664: close($config);
12665: }
12666: }
12667: }
12668: }
12669:
12670:
1.862 albertel 12671: BEGIN {
12672:
12673: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12674: unless ($readit) {
12675: {
12676: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12677: %perlvar = (%perlvar,%{$configvars});
12678: }
12679:
12680:
1.1 albertel 12681: # ------------------------------------------------------ Read spare server file
12682: {
1.448 albertel 12683: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12684:
12685: while (my $configline=<$config>) {
12686: chomp($configline);
1.284 matthew 12687: if ($configline) {
1.784 albertel 12688: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12689: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12690: push(@{ $spareid{$type} }, $host);
1.1 albertel 12691: }
12692: }
1.448 albertel 12693: close($config);
1.1 albertel 12694: }
1.11 www 12695: # ------------------------------------------------------------ Read permissions
12696: {
1.448 albertel 12697: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12698:
12699: while (my $configline=<$config>) {
1.448 albertel 12700: chomp($configline);
12701: if ($configline) {
12702: my ($role,$perm)=split(/ /,$configline);
12703: if ($perm ne '') { $pr{$role}=$perm; }
12704: }
1.11 www 12705: }
1.448 albertel 12706: close($config);
1.11 www 12707: }
12708:
12709: # -------------------------------------------- Read plain texts for permissions
12710: {
1.448 albertel 12711: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12712:
12713: while (my $configline=<$config>) {
1.448 albertel 12714: chomp($configline);
12715: if ($configline) {
1.742 raeburn 12716: my ($short,@plain)=split(/:/,$configline);
12717: %{$prp{$short}} = ();
12718: if (@plain > 0) {
12719: $prp{$short}{'std'} = $plain[0];
12720: for (my $i=1; $i<@plain; $i++) {
12721: $prp{$short}{'alt'.$i} = $plain[$i];
12722: }
12723: }
1.448 albertel 12724: }
1.135 www 12725: }
1.448 albertel 12726: close($config);
1.135 www 12727: }
12728:
12729: # ---------------------------------------------------------- Read package table
12730: {
1.448 albertel 12731: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12732:
12733: while (my $configline=<$config>) {
1.483 albertel 12734: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12735: chomp($configline);
12736: my ($short,$plain)=split(/:/,$configline);
12737: my ($pack,$name)=split(/\&/,$short);
12738: if ($plain ne '') {
12739: $packagetab{$pack.'&'.$name.'&name'}=$name;
12740: $packagetab{$short}=$plain;
12741: }
1.11 www 12742: }
1.448 albertel 12743: close($config);
1.329 matthew 12744: }
12745:
1.1172.2.27 raeburn 12746: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 12747:
1.1172.2.27 raeburn 12748: &load_loncaparevs();
12749:
12750: # ------------------------------------------------------- Read serverhostID table
12751:
12752: &load_serverhomeIDs();
1.1074 raeburn 12753:
1.1172.2.27 raeburn 12754: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12755: {
12756: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12757: if (-e $file) {
12758: my $parser = HTML::LCParser->new($file);
12759: while (my $token = $parser->get_token()) {
12760: if ($token->[0] eq 'S') {
12761: my $item = $token->[1];
12762: my $name = $token->[2]{'name'};
12763: my $value = $token->[2]{'value'};
12764: if ($item ne '' && $name ne '' && $value ne '') {
12765: my $release = $parser->get_text();
12766: $release =~ s/(^\s*|\s*$ )//gx;
12767: $needsrelease{$item.':'.$name.':'.$value} = $release;
12768: }
12769: }
12770: }
12771: }
1.1073 raeburn 12772: }
12773:
1.1138 raeburn 12774: # ---------------------------------------------------------- Read managers table
12775: {
12776: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12777: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12778: while (my $configline=<$config>) {
12779: chomp($configline);
12780: next if ($configline =~ /^\#/);
12781: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12782: $managerstab{$configline} = 1;
12783: }
12784: }
12785: close($config);
12786: }
12787: }
12788: }
12789:
1.329 matthew 12790: # ------------- set up temporary directory
12791: {
1.1117 foxr 12792: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12793:
1.11 www 12794: }
12795:
1.794 albertel 12796: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12797: 'compress_threshold'=> 20_000,
12798: });
1.185 www 12799:
1.281 www 12800: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12801: $dumpcount=0;
1.958 www 12802: $locknum=0;
1.22 www 12803:
1.163 harris41 12804: &logtouch();
1.672 albertel 12805: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12806: $readit=1;
1.564 albertel 12807: {
12808: use integer;
12809: my $test=(2**32)+1;
1.568 albertel 12810: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12811: &logthis(" Detected 64bit platform ($_64bit)");
12812: }
1.195 www 12813: }
1.1 albertel 12814: }
1.179 www 12815:
1.1 albertel 12816: 1;
1.191 harris41 12817: __END__
12818:
1.243 albertel 12819: =pod
12820:
1.191 harris41 12821: =head1 NAME
12822:
1.243 albertel 12823: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12824:
12825: =head1 SYNOPSIS
12826:
1.243 albertel 12827: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12828:
12829: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12830:
1.243 albertel 12831: Common parameters:
12832:
12833: =over 4
12834:
12835: =item *
12836:
12837: $uname : an internal username (if $cname expecting a course Id specifically)
12838:
12839: =item *
12840:
12841: $udom : a domain (if $cdom expecting a course's domain specifically)
12842:
12843: =item *
12844:
12845: $symb : a resource instance identifier
12846:
12847: =item *
12848:
12849: $namespace : the name of a .db file that contains the data needed or
12850: being set.
12851:
12852: =back
12853:
1.394 bowersj2 12854: =head1 OVERVIEW
1.191 harris41 12855:
1.394 bowersj2 12856: lonnet provides subroutines which interact with the
12857: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12858: about classes, users, and resources.
1.243 albertel 12859:
12860: For many of these objects you can also use this to store data about
12861: them or modify them in various ways.
1.191 harris41 12862:
1.394 bowersj2 12863: =head2 Symbs
1.191 harris41 12864:
1.394 bowersj2 12865: To identify a specific instance of a resource, LON-CAPA uses symbols
12866: or "symbs"X<symb>. These identifiers are built from the URL of the
12867: map, the resource number of the resource in the map, and the URL of
12868: the resource itself. The latter is somewhat redundant, but might help
12869: if maps change.
12870:
12871: An example is
12872:
12873: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12874:
12875: The respective map entry is
12876:
12877: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12878: title="Problem 2">
12879: </resource>
12880:
12881: Symbs are used by the random number generator, as well as to store and
12882: restore data specific to a certain instance of for example a problem.
12883:
12884: =head2 Storing And Retrieving Data
12885:
12886: X<store()>X<cstore()>X<restore()>Three of the most important functions
12887: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12888: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12889: is is the non-critical message twin of cstore. These functions are for
12890: handlers to store a perl hash to a user's permanent data space in an
12891: easy manner, and to retrieve it again on another call. It is expected
12892: that a handler would use this once at the beginning to retrieve data,
12893: and then again once at the end to send only the new data back.
12894:
12895: The data is stored in the user's data directory on the user's
12896: homeserver under the ID of the course.
12897:
12898: The hash that is returned by restore will have all of the previous
12899: value for all of the elements of the hash.
12900:
12901: Example:
12902:
12903: #creating a hash
12904: my %hash;
12905: $hash{'foo'}='bar';
12906:
12907: #storing it
12908: &Apache::lonnet::cstore(\%hash);
12909:
12910: #changing a value
12911: $hash{'foo'}='notbar';
12912:
12913: #adding a new value
12914: $hash{'bar'}='foo';
12915: &Apache::lonnet::cstore(\%hash);
12916:
12917: #retrieving the hash
12918: my %history=&Apache::lonnet::restore();
12919:
12920: #print the hash
12921: foreach my $key (sort(keys(%history))) {
12922: print("\%history{$key} = $history{$key}");
12923: }
12924:
12925: Will print out:
1.191 harris41 12926:
1.394 bowersj2 12927: %history{1:foo} = bar
12928: %history{1:keys} = foo:timestamp
12929: %history{1:timestamp} = 990455579
12930: %history{2:bar} = foo
12931: %history{2:foo} = notbar
12932: %history{2:keys} = foo:bar:timestamp
12933: %history{2:timestamp} = 990455580
12934: %history{bar} = foo
12935: %history{foo} = notbar
12936: %history{timestamp} = 990455580
12937: %history{version} = 2
12938:
12939: Note that the special hash entries C<keys>, C<version> and
12940: C<timestamp> were added to the hash. C<version> will be equal to the
12941: total number of versions of the data that have been stored. The
12942: C<timestamp> attribute will be the UNIX time the hash was
12943: stored. C<keys> is available in every historical section to list which
12944: keys were added or changed at a specific historical revision of a
12945: hash.
12946:
12947: B<Warning>: do not store the hash that restore returns directly. This
12948: will cause a mess since it will restore the historical keys as if the
12949: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12950:
1.394 bowersj2 12951: Calling convention:
1.191 harris41 12952:
1.1172.2.27 raeburn 12953: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 12954: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 12955:
1.394 bowersj2 12956: For more detailed information, see lonnet specific documentation.
1.191 harris41 12957:
1.394 bowersj2 12958: =head1 RETURN MESSAGES
1.191 harris41 12959:
1.394 bowersj2 12960: =over 4
1.191 harris41 12961:
1.394 bowersj2 12962: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12963:
1.394 bowersj2 12964: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12965: when the connection is brought back up
1.191 harris41 12966:
1.394 bowersj2 12967: =item * B<con_failed>: unable to contact remote host and unable to save message
12968: for later delivery
1.191 harris41 12969:
1.967 bisitz 12970: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12971:
1.394 bowersj2 12972: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12973: that was requested
1.191 harris41 12974:
1.243 albertel 12975: =back
1.191 harris41 12976:
1.243 albertel 12977: =head1 PUBLIC SUBROUTINES
1.191 harris41 12978:
1.243 albertel 12979: =head2 Session Environment Functions
1.191 harris41 12980:
1.243 albertel 12981: =over 4
1.191 harris41 12982:
1.394 bowersj2 12983: =item *
12984: X<appenv()>
1.949 raeburn 12985: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12986: the user envirnoment file, and will be restored for each access this
1.620 albertel 12987: user makes during this session, also modifies the %env for the current
1.949 raeburn 12988: process. Optional rolesarrayref - if defined contains a reference to an array
12989: of roles which are exempt from the restriction on modifying user.role entries
12990: in the user's environment.db and in %env.
1.191 harris41 12991:
12992: =item *
1.394 bowersj2 12993: X<delenv()>
1.987 raeburn 12994: B<delenv($delthis,$regexp)>: removes all items from the session
12995: environment file that begin with $delthis. If the
12996: optional second arg - $regexp - is true, $delthis is treated as a
12997: regular expression, otherwise \Q$delthis\E is used.
12998: The values are also deleted from the current processes %env.
1.191 harris41 12999:
1.795 albertel 13000: =item * get_env_multiple($name)
13001:
13002: gets $name from the %env hash, it seemlessly handles the cases where multiple
13003: values may be defined and end up as an array ref.
13004:
13005: returns an array of values
13006:
1.243 albertel 13007: =back
13008:
13009: =head2 User Information
1.191 harris41 13010:
1.243 albertel 13011: =over 4
1.191 harris41 13012:
13013: =item *
1.394 bowersj2 13014: X<queryauthenticate()>
13015: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13016: authentication scheme
13017:
13018: =item *
1.394 bowersj2 13019: X<authenticate()>
1.1073 raeburn 13020: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13021: authenticate user from domain's lib servers (first use the current
13022: one). C<$upass> should be the users password.
1.1073 raeburn 13023: $checkdefauth is optional (value is 1 if a check should be made to
13024: authenticate user using default authentication method, and allow
13025: account creation if username does not have account in the domain).
13026: $clientcancheckhost is optional (value is 1 if checking whether the
13027: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13028:
13029: =item *
1.394 bowersj2 13030: X<homeserver()>
13031: B<homeserver($uname,$udom)>: find the server which has
13032: the user's directory and files (there must be only one), this caches
13033: the answer, and also caches if there is a borken connection.
1.191 harris41 13034:
13035: =item *
1.394 bowersj2 13036: X<idget()>
13037: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13038: (IDs are a unique resource in a domain, there must be only 1 ID per
13039: username, and only 1 username per ID in a specific domain) (returns
13040: hash: id=>name,id=>name)
1.191 harris41 13041:
13042: =item *
1.394 bowersj2 13043: X<idrget()>
13044: B<idrget($udom,@unames)>: find the IDs behind a list of
13045: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13046:
13047: =item *
1.394 bowersj2 13048: X<idput()>
13049: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 13050:
13051: =item *
1.394 bowersj2 13052: X<rolesinit()>
1.1169 droeschl 13053: B<rolesinit($udom,$username)>: get user privileges.
13054: returns user role, first access and timer interval hashes
1.243 albertel 13055:
13056: =item *
1.1171 droeschl 13057: X<privileged()>
13058: B<privileged($username,$domain)>: returns a true if user has a
13059: privileged and active role (i.e. su or dc), false otherwise.
13060:
13061: =item *
1.551 albertel 13062: X<getsection()>
13063: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13064: course $cname, return section name/number or '' for "not in course"
13065: and '-1' for "no section"
13066:
13067: =item *
1.394 bowersj2 13068: X<userenvironment()>
13069: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13070: passed in @what from the requested user's environment, returns a hash
13071:
1.858 raeburn 13072: =item *
13073: X<userlog_query()>
1.859 albertel 13074: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13075: activity.log file. %filters defines filters applied when parsing the
13076: log file. These can be start or end timestamps, or the type of action
13077: - log to look for Login or Logout events, check for Checkin or
13078: Checkout, role for role selection. The response is in the form
13079: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13080: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13081:
1.243 albertel 13082: =back
13083:
13084: =head2 User Roles
13085:
13086: =over 4
13087:
13088: =item *
13089:
1.1172.2.65 raeburn 13090: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13091: returns codes for allowed actions.
13092:
13093: The first argument is required, all others are optional.
13094:
13095: $priv is the privilege being checked.
13096: $uri contains additional information about what is being checked for access (e.g.,
13097: URL, course ID etc.).
13098: $symb is the unique resource instance identifier in a course; if needed,
13099: but not provided, it will be retrieved via a call to &symbread().
13100: $role is the role for which a priv is being checked (only used if priv is evb).
13101: $clientip is the user's IP address (only used when checking for access to portfolio
13102: files).
13103: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13104: prevents recursive calls to &allowed.
13105:
1.243 albertel 13106: F: full access
13107: U,I,K: authentication modes (cxx only)
13108: '': forbidden
13109: 1: user needs to choose course
13110: 2: browse allowed
1.766 albertel 13111: A: passphrase authentication needed
1.1172.2.65 raeburn 13112: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13113:
13114: =item *
13115:
1.1172.2.13 raeburn 13116: constructaccess($url,$setpriv) : check for access to construction space URL
13117:
13118: See if the owner domain and name in the URL match those in the
13119: expected environment. If so, return three element list
13120: ($ownername,$ownerdomain,$ownerhome).
13121:
13122: Otherwise return the null string.
13123:
13124: If second argument 'setpriv' is true, it assigns the privileges,
13125: and returns the same three element list, unless the owner has
13126: blocked "ad hoc" Domain Coordinator access to the Author Space,
13127: in which case the null string is returned.
13128:
13129: =item *
13130:
1.243 albertel 13131: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
13132: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
13133: and course level
13134:
13135: =item *
13136:
1.988 raeburn 13137: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13138: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13139: $type is Course (default) or Community.
1.988 raeburn 13140: If $forcedefault evaluates to true, text returned will be default
13141: text for $type. Otherwise, if this is a course, the text returned
13142: will be a custom name for the role (if defined in the course's
13143: environment). If no custom name is defined the default is returned.
13144:
1.832 raeburn 13145: =item *
13146:
1.1172.2.23 raeburn 13147: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13148: All arguments are optional. Returns a hash of a roles, either for
13149: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13150: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13151: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13152: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13153: For each key, value is set to colon-separated start and end times for
13154: the role. If no username and domain are specified, will default to
1.934 raeburn 13155: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13156: of role statuses (active, future or previous), roles
13157: (e.g., cc,in, st etc.) and domains of the roles which can be used
13158: to restrict the list of roles reported. If no array ref is
13159: provided for types, will default to return only active roles.
1.834 albertel 13160:
1.1172.2.13 raeburn 13161: =item *
13162:
13163: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
13164: user: $uname:$udom has a role in the course: $cdom_$cnum.
13165:
13166: Additional optional arguments are: $type (if role checking is to be restricted
13167: to certain user status types -- previous (expired roles), active (currently
13168: available roles) or future (roles available in the future), and
13169: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 13170: have active Domain Coordinator role in course's domain or in additional
13171: domains (specified in 'Domains to check for privileged users' in course
13172: environment -- set via: Course Settings -> Classlists and staff listing).
13173:
13174: =item *
13175:
13176: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13177: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13178: $possdomains and $possroles are optional array refs -- to domains to check and
13179: roles to check. If $possdomains is not specified, a dump will be done of the
13180: users' roles.db to check for a dc or su role in any domain. This can be
13181: time consuming if &privileged is called repeatedly (e.g., when displaying a
13182: classlist), so in such cases, supplying a $possdomains array is preferred, as
13183: this then allows &privileged_by_domain() to be used, which caches the identity
13184: of privileged users, eliminating the need for repeated calls to &dump().
13185:
13186: =item *
13187:
13188: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13189: where the outer hash keys are domains specified in the $possdomains array ref,
13190: next inner hash keys are privileged roles specified in the $roles array ref,
13191: and the innermost hash contains key = value pairs for username:domain = end:start
13192: for active or future "privileged" users with that role in that domain. To avoid
13193: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13194: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 13195:
1.243 albertel 13196: =back
13197:
13198: =head2 User Modification
13199:
13200: =over 4
13201:
13202: =item *
13203:
1.957 raeburn 13204: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13205: user for the level given by URL. Optional start and end dates (leave empty
13206: string or zero for "no date")
1.191 harris41 13207:
13208: =item *
13209:
1.243 albertel 13210: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13211: change a users, password, possible return values are: ok,
13212: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13213: refused
1.191 harris41 13214:
13215: =item *
13216:
1.243 albertel 13217: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13218:
13219: =item *
13220:
1.1058 raeburn 13221: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13222: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13223:
13224: will update user information (firstname,middlename,lastname,generation,
13225: permanentemail), and if forceid is true, student/employee ID also.
13226: A user's institutional affiliation(s) can also be updated.
13227: User information fields will not be overwritten with empty entries
13228: unless the field is included in the $candelete array reference.
13229: This array is included when a single user is modified via "Manage Users",
13230: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13231:
13232: =item *
13233:
1.286 matthew 13234: modifystudent
13235:
1.957 raeburn 13236: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 13237: The course id is resolved based on the current user's environment.
13238: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13239: associated with a course.
13240:
1.297 matthew 13241: This call is essentially a wrapper for lonnet::modifyuser and
13242: lonnet::modify_student_enrollment
1.286 matthew 13243:
13244: Inputs:
13245:
13246: =over 4
13247:
1.957 raeburn 13248: =item B<$udom> Student's loncapa domain
1.286 matthew 13249:
1.957 raeburn 13250: =item B<$uname> Student's loncapa login name
1.286 matthew 13251:
1.964 bisitz 13252: =item B<$uid> Student/Employee ID
1.286 matthew 13253:
1.957 raeburn 13254: =item B<$umode> Student's authentication mode
1.286 matthew 13255:
1.957 raeburn 13256: =item B<$upass> Student's password
1.286 matthew 13257:
1.957 raeburn 13258: =item B<$first> Student's first name
1.286 matthew 13259:
1.957 raeburn 13260: =item B<$middle> Student's middle name
1.286 matthew 13261:
1.957 raeburn 13262: =item B<$last> Student's last name
1.286 matthew 13263:
1.957 raeburn 13264: =item B<$gene> Student's generation
1.286 matthew 13265:
1.957 raeburn 13266: =item B<$usec> Student's section in course
1.286 matthew 13267:
13268: =item B<$end> Unix time of the roles expiration
13269:
13270: =item B<$start> Unix time of the roles start date
13271:
13272: =item B<$forceid> If defined, allow $uid to be changed
13273:
13274: =item B<$desiredhome> server to use as home server for student
13275:
1.957 raeburn 13276: =item B<$email> Student's permanent e-mail address
13277:
13278: =item B<$type> Type of enrollment (auto or manual)
13279:
1.963 raeburn 13280: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13281:
13282: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13283:
1.963 raeburn 13284: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13285:
1.963 raeburn 13286: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13287:
1.1172.2.19 raeburn 13288: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13289:
13290: =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 13291:
1.286 matthew 13292: =back
1.297 matthew 13293:
13294: =item *
13295:
13296: modify_student_enrollment
13297:
1.1172.2.31 raeburn 13298: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13299: 'role.request.course' must be defined for this function to proceed.
13300:
13301: Inputs:
13302:
13303: =over 4
13304:
1.1172.2.31 raeburn 13305: =item $udom, student's domain
1.297 matthew 13306:
1.1172.2.31 raeburn 13307: =item $uname, student's name
1.297 matthew 13308:
1.1172.2.31 raeburn 13309: =item $uid, student's user id
1.297 matthew 13310:
1.1172.2.31 raeburn 13311: =item $first, student's first name
1.297 matthew 13312:
13313: =item $middle
13314:
13315: =item $last
13316:
13317: =item $gene
13318:
13319: =item $usec
13320:
13321: =item $end
13322:
13323: =item $start
13324:
1.957 raeburn 13325: =item $type
13326:
13327: =item $locktype
13328:
13329: =item $cid
13330:
13331: =item $selfenroll
13332:
13333: =item $context
13334:
1.1172.2.19 raeburn 13335: =item $credits, number of credits student will earn from this class
13336:
1.297 matthew 13337: =back
13338:
1.191 harris41 13339:
13340: =item *
13341:
1.243 albertel 13342: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13343: custom role; give a custom role to a user for the level given by URL. Specify
13344: name and domain of role author, and role name
1.191 harris41 13345:
13346: =item *
13347:
1.243 albertel 13348: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13349:
13350: =item *
13351:
1.243 albertel 13352: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13353:
13354: =back
13355:
13356: =head2 Course Infomation
13357:
13358: =over 4
1.191 harris41 13359:
13360: =item *
13361:
1.1118 foxr 13362: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 13363: specified course id, including all environment settings for the
13364: course, the description of the course will be in the hash under the
13365: key 'description'
1.191 harris41 13366:
1.1118 foxr 13367: $options is an optional parameter that if supplied is a hash reference that controls
13368: what how this function works. It has the following key/values:
13369:
13370: =over 4
13371:
13372: =item freshen_cache
13373:
13374: If defined, and the environment cache for the course is valid, it is
13375: returned in the returned hash.
13376:
13377: =item one_time
13378:
13379: If defined, the last cache time is set to _now_
13380:
13381: =item user
13382:
13383: If defined, the supplied username is used instead of the current user.
13384:
13385:
13386: =back
13387:
1.191 harris41 13388: =item *
13389:
1.624 albertel 13390: resdata($name,$domain,$type,@which) : request for current parameter
13391: setting for a specific $type, where $type is either 'course' or 'user',
13392: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 13393: answers for 10 minutes.
1.243 albertel 13394:
1.877 foxr 13395: =item *
13396:
13397: get_courseresdata($courseid, $domain) : dump the entire course resource
13398: data base, returning a hash that is keyed by the resource name and has
13399: values that are the resource value. I believe that the timestamps and
13400: versions are also returned.
13401:
1.1172.2.31 raeburn 13402: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13403: supplemental content area. This routine caches the number of files for
13404: 10 minutes.
13405:
1.243 albertel 13406: =back
13407:
13408: =head2 Course Modification
13409:
13410: =over 4
1.191 harris41 13411:
13412: =item *
13413:
1.243 albertel 13414: writecoursepref($courseid,%prefs) : write preferences (environment
13415: database) for a course
1.191 harris41 13416:
13417: =item *
13418:
1.1011 raeburn 13419: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13420:
13421: =item *
13422:
1.1038 raeburn 13423: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 13424:
1.1167 droeschl 13425: =item *
13426:
13427: is_course($courseid), is_course($cdom, $cnum)
13428:
13429: Accepts either a combined $courseid (in the form of domain_courseid) or the
13430: two component version $cdom, $cnum. It checks if the specified course exists.
13431:
13432: Returns:
13433: undef if the course doesn't exist, otherwise
13434: in scalar context the combined courseid.
13435: in list context the two components of the course identifier, domain and
13436: courseid.
13437:
1.243 albertel 13438: =back
13439:
13440: =head2 Resource Subroutines
13441:
13442: =over 4
1.191 harris41 13443:
13444: =item *
13445:
1.243 albertel 13446: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13447:
13448: =item *
13449:
1.243 albertel 13450: repcopy($filename) : subscribes to the requested file, and attempts to
13451: replicate from the owning library server, Might return
1.607 raeburn 13452: 'unavailable', 'not_found', 'forbidden', 'ok', or
13453: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13454: resource. Expects the local filesystem pathname
13455: (/home/httpd/html/res/....)
13456:
13457: =back
13458:
13459: =head2 Resource Information
13460:
13461: =over 4
1.191 harris41 13462:
13463: =item *
13464:
1.1172.2.28 raeburn 13465: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13466: and returns the value of a variety of different possible values,
13467: $varname should be a request string, and the other parameters can be
13468: used to specify who and what one is asking about. Ordinarily, $cid
13469: does not need to be specified, as it is retrived from
13470: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13471: within lonuserstate::loadmap() when initializing a course, before
13472: $env{'request.course.id'} has been set, so it needs to be provided
13473: in that one case.
1.243 albertel 13474:
13475: Possible values for $varname are environment.lastname (or other item
13476: from the envirnment hash), user.name (or someother aspect about the
13477: user), resource.0.maxtries (or some other part and parameter of a
13478: resource)
1.204 albertel 13479:
13480: =item *
13481:
1.243 albertel 13482: directcondval($number) : get current value of a condition; reads from a state
13483: string
1.204 albertel 13484:
13485: =item *
13486:
1.243 albertel 13487: condval($condidx) : value of condition index based on state
1.204 albertel 13488:
13489: =item *
13490:
1.243 albertel 13491: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13492: resource's metadata, $what should be either a specific key, or either
13493: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13494: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13495:
13496: this function automatically caches all requests
1.191 harris41 13497:
13498: =item *
13499:
1.243 albertel 13500: metadata_query($query,$custom,$customshow) : make a metadata query against the
13501: network of library servers; returns file handle of where SQL and regex results
13502: will be stored for query
1.191 harris41 13503:
13504: =item *
13505:
1.1172.2.66 raeburn 13506: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
13507: return symbolic list entry (all arguments optional).
13508:
13509: Args: filename is the filename (including path) for the file for which a symb
13510: is required; donotrecurse, if true will prevent calls to allowed() being made
13511: to check access status if more than one resource was found in the bighash
13512: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
13513: a randompick); ignorecachednull, if true will prevent a symb of '' being
13514: returned if $env{$cache_str} is defined as ''; checkforblock if true will
13515: cause possible symbs to be checked to determine if they are subject to content
13516: blocking, if so they will not be included as possible symbs; possibles is a
13517: ref to a hash, which, as a side effect, will be populated with all possible
13518: symbs (content blocking not tested).
13519:
1.243 albertel 13520: returns the data handle
1.191 harris41 13521:
13522: =item *
13523:
1.1172.2.17 raeburn 13524: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 13525: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13526: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 13527: on failure, user must be in a course, as it assumes the existence of
13528: the course initial hash, and uses $env('request.course.id'}. The third
13529: arg is an optional reference to a scalar. If this arg is passed in the
13530: call to symbverify, it will be set to 1 if the symb has been set to be
13531: encrypted; otherwise it will be null.
1.243 albertel 13532:
1.191 harris41 13533: =item *
13534:
1.243 albertel 13535: symbclean($symb) : removes versions numbers from a symb, returns the
13536: cleaned symb
1.191 harris41 13537:
13538: =item *
13539:
1.243 albertel 13540: is_on_map($uri) : checks if the $uri is somewhere on the current
13541: course map, user must be in a course for it to work.
1.191 harris41 13542:
13543: =item *
13544:
1.243 albertel 13545: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13546:
13547: =item *
13548:
1.243 albertel 13549: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13550: a random seed, all arguments are optional, if they aren't sent it uses the
13551: environment to derive them. Note: if symb isn't sent and it can't get one
13552: from &symbread it will use the current time as its return value
1.191 harris41 13553:
13554: =item *
13555:
1.243 albertel 13556: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13557: unfakeable, receipt
1.191 harris41 13558:
13559: =item *
13560:
1.620 albertel 13561: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13562:
13563: =item *
13564:
1.243 albertel 13565: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13566:
13567: =item *
13568:
1.243 albertel 13569: 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 13570:
13571: =item *
13572:
1.243 albertel 13573: 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 13574:
13575: =item *
13576:
1.243 albertel 13577: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13578:
13579: =item *
13580:
1.243 albertel 13581: devalidate($symb) : devalidate temporary spreadsheet calculations,
13582: forcing spreadsheet to reevaluate the resource scores next time.
13583:
1.1172.2.13 raeburn 13584: =item *
13585:
13586: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13587: when viewing in course context.
13588:
13589: input: six args -- filename (decluttered), course number, course domain,
13590: url, symb (if registered) and group (if this is a
13591: group item -- e.g., bulletin board, group page etc.).
13592:
13593: output: array of five scalars --
13594: $cfile -- url for file editing if editable on current server
13595: $home -- homeserver of resource (i.e., for author if published,
13596: or course if uploaded.).
13597: $switchserver -- 1 if server switch will be needed.
13598: $forceedit -- 1 if icon/link should be to go to edit mode
13599: $forceview -- 1 if icon/link should be to go to view mode
13600:
13601: =item *
13602:
13603: is_course_upload($file,$cnum,$cdom)
13604:
13605: Used in course context to determine if current file was uploaded to
13606: the course (i.e., would be found in /userfiles/docs on the course's
13607: homeserver.
13608:
13609: input: 3 args -- filename (decluttered), course number and course domain.
13610: output: boolean -- 1 if file was uploaded.
13611:
1.243 albertel 13612: =back
13613:
13614: =head2 Storing/Retreiving Data
13615:
13616: =over 4
1.191 harris41 13617:
13618: =item *
13619:
1.1172.2.64 raeburn 13620: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13621: permanently for this url; hashref needs to be given and should be a \%hashname;
13622: the remaining args aren't required and if they aren't passed or are '' they will
13623: be derived from the env (with the exception of $laststore, which is an
13624: optional arg used when a user's submission is stored in grading).
13625: $laststore is $version=$timestamp, where $version is the most recent version
13626: number retrieved for the corresponding $symb in the $namespace db file, and
13627: $timestamp is the timestamp for that transaction (UNIX time).
13628: $laststore is currently only passed when cstore() is called by
13629: structuretags::finalize_storage().
1.191 harris41 13630:
13631: =item *
13632:
1.1172.2.64 raeburn 13633: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13634: but uses critical subroutine
1.191 harris41 13635:
13636: =item *
13637:
1.243 albertel 13638: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13639: all args are optional
1.191 harris41 13640:
13641: =item *
13642:
1.717 albertel 13643: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13644: dumps the complete (or key matching regexp) namespace into a hash
13645: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13646: normally &store()ed into
13647:
13648: $range should be either an integer '100' (give me the first 100
13649: matching records)
13650: or be two integers sperated by a - with no spaces
13651: '30-50' (give me the 30th through the 50th matching
13652: records)
13653:
13654:
13655: =item *
13656:
1.1172.2.59 raeburn 13657: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 13658: replaces a &store() version of data with a replacement set of data
13659: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 13660: reference. If $tolog is true, the transaction is logged in the courselog
13661: with an action=PUTSTORE.
1.717 albertel 13662:
13663: =item *
13664:
1.243 albertel 13665: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13666: works very similar to store/cstore, but all data is stored in a
13667: temporary location and can be reset using tmpreset, $storehash should
13668: be a hash reference, returns nothing on success
1.191 harris41 13669:
13670: =item *
13671:
1.243 albertel 13672: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13673: similar to restore, but all data is stored in a temporary location and
13674: can be reset using tmpreset. Returns a hash of values on success,
13675: error string otherwise.
1.191 harris41 13676:
13677: =item *
13678:
1.243 albertel 13679: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13680: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13681:
13682: =item *
13683:
1.243 albertel 13684: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13685: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13686:
13687: =item *
13688:
1.243 albertel 13689: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13690: namesp ($udom and $uname are optional)
1.191 harris41 13691:
13692: =item *
13693:
1.702 albertel 13694: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13695: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13696: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13697:
1.702 albertel 13698: $range should be either an integer '100' (give me the first 100
13699: matching records)
13700: or be two integers sperated by a - with no spaces
13701: '30-50' (give me the 30th through the 50th matching
13702: records)
1.449 matthew 13703: =item *
13704:
13705: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13706: $store can be a scalar, an array reference, or if the amount to be
13707: incremented is > 1, a hash reference.
13708:
13709: ($udom and $uname are optional)
1.191 harris41 13710:
13711: =item *
13712:
1.243 albertel 13713: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13714: ($udom and $uname are optional)
1.191 harris41 13715:
13716: =item *
13717:
1.243 albertel 13718: cput($namespace,$storehash,$udom,$uname) : critical put
13719: ($udom and $uname are optional)
1.191 harris41 13720:
13721: =item *
13722:
1.748 albertel 13723: newput($namespace,$storehash,$udom,$uname) :
13724:
13725: Attempts to store the items in the $storehash, but only if they don't
13726: currently exist, if this succeeds you can be certain that you have
13727: successfully created a new key value pair in the $namespace db.
13728:
13729:
13730: Args:
13731: $namespace: name of database to store values to
13732: $storehash: hashref to store to the db
13733: $udom: (optional) domain of user containing the db
13734: $uname: (optional) name of user caontaining the db
13735:
13736: Returns:
13737: 'ok' -> succeeded in storing all keys of $storehash
13738: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13739: least <key> already existed in the db (other
13740: requested keys may also already exist)
1.967 bisitz 13741: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13742: 'con_lost' -> unable to contact request server
13743: 'refused' -> action was not allowed by remote machine
13744:
13745:
13746: =item *
13747:
1.243 albertel 13748: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13749: reference filled in from namesp (encrypts the return communication)
13750: ($udom and $uname are optional)
1.191 harris41 13751:
13752: =item *
13753:
1.243 albertel 13754: log($udom,$name,$home,$message) : write to permanent log for user; use
13755: critical subroutine
13756:
1.806 raeburn 13757: =item *
13758:
1.860 raeburn 13759: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13760: array reference filled in from namespace found in domain level on either
13761: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13762:
13763: =item *
13764:
1.860 raeburn 13765: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13766: domain level either on specified domain server ($uhome) or primary domain
13767: server ($udom and $uhome are optional)
1.806 raeburn 13768:
1.943 raeburn 13769: =item *
13770:
1.1172.2.35 raeburn 13771: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13772: for: authentication, language, quotas, timezone, date locale, and portal URL in
13773: the target domain.
13774:
13775: May also include additional key => value pairs for the following groups:
13776:
13777: =over
13778:
13779: =item
13780: disk quotas (MB allocated by default to portfolios and authoring spaces).
13781:
13782: =over
13783:
13784: =item defaultquota, authorquota
13785:
13786: =back
13787:
13788: =item
13789: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13790: portfolio for users).
13791:
13792: =over
13793:
13794: =item
13795: aboutme, blog, webdav, portfolio
13796:
13797: =back
13798:
13799: =item
13800: requestcourses: ability to request courses, and how requests are processed.
13801:
13802: =over
13803:
13804: =item
1.1172.2.37 raeburn 13805: official, unofficial, community, textbook
1.1172.2.35 raeburn 13806:
13807: =back
13808:
13809: =item
13810: inststatus: types of institutional affiliation, and order in which they are displayed.
13811:
13812: =over
13813:
13814: =item
1.1172.2.44 raeburn 13815: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 13816:
13817: =back
13818:
13819: =item
13820: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13821: for course's uploaded content.
13822:
13823: =over
13824:
13825: =item
1.1172.2.68 raeburn 13826: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13827: communityquota, textbookquota
1.1172.2.35 raeburn 13828:
13829: =back
13830:
13831: =item
13832: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13833: on your servers.
13834:
13835: =over
13836:
13837: =item
13838: remotesessions, hostedsessions
13839:
13840: =back
13841:
13842: =back
13843:
13844: In cases where a domain coordinator has never used the "Set Domain Configuration"
13845: utility to create a configuration.db file on a domain's primary library server
13846: only the following domain defaults: auth_def, auth_arg_def, lang_def
13847: -- corresponding values are authentication type (internal, krb4, krb5,
13848: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13849: will be available. Values are retrieved from cache (if current), unless the
13850: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13851: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13852:
13853: Typical usage:
1.943 raeburn 13854:
1.1172.2.35 raeburn 13855: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13856:
1.243 albertel 13857: =back
13858:
13859: =head2 Network Status Functions
13860:
13861: =over 4
1.191 harris41 13862:
13863: =item *
13864:
1.1137 raeburn 13865: dirlist() : return directory list based on URI (first arg).
13866:
13867: Inputs: 1 required, 5 optional.
13868:
13869: =over
13870:
13871: =item
13872: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13873:
13874: =item
13875: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13876:
13877: =item
13878: $username - username of user/course to be listed. Extracted from $uri if absent.
13879:
13880: =item
13881: $getpropath - boolean: 1 if prepend path using &propath().
13882:
13883: =item
13884: $getuserdir - boolean: 1 if prepend path for "userfiles".
13885:
13886: =item
13887: $alternateRoot - path to prepend in place of path from $uri.
13888:
13889: =back
13890:
13891: Returns: Array of up to two items.
13892:
13893: =over
13894:
13895: a reference to an array of files/subdirectories
13896:
13897: =over
13898:
13899: Each element in the array of files/subdirectories is a & separated list of
13900: item name and the result of running stat on the item. If dirlist was requested
13901: for a file instead of a directory, the item name will be ''. For a directory
13902: listing, if the item is a metadata file, the element will end &N&M
13903: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13904: default copyright set (1).
13905:
13906: =back
13907:
13908: a scalar containing error condition (if encountered).
13909:
13910: =over
13911:
13912: =item
13913: no_host (no homeserver identified for $username:$domain).
13914:
13915: =item
13916: no_such_host (server contacted for listing not identified as valid host).
13917:
13918: =item
13919: con_lost (connection to remote server failed).
13920:
13921: =item
13922: refused (invalid $username:$domain received on lond side).
13923:
13924: =item
13925: no_such_dir (directory at specified path on lond side does not exist).
13926:
13927: =item
13928: empty (directory at specified path on lond side is empty).
13929:
13930: =over
13931:
13932: This is currently not encountered because the &ls3, &ls2,
13933: &ls (_handler) routines on the lond side do not filter out
13934: . and .. from a directory listing.
13935:
13936: =back
13937:
13938: =back
13939:
13940: =back
1.191 harris41 13941:
13942: =item *
13943:
1.243 albertel 13944: spareserver() : find server with least workload from spare.tab
13945:
1.986 foxr 13946:
13947: =item *
13948:
13949: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13950: if there is no corresponding loncapa host.
13951:
1.243 albertel 13952: =back
13953:
1.986 foxr 13954:
1.243 albertel 13955: =head2 Apache Request
13956:
13957: =over 4
1.191 harris41 13958:
13959: =item *
13960:
1.243 albertel 13961: ssi($url,%hash) : server side include, does a complete request cycle on url to
13962: localhost, posts hash
13963:
13964: =back
13965:
13966: =head2 Data to String to Data
13967:
13968: =over 4
1.191 harris41 13969:
13970: =item *
13971:
1.243 albertel 13972: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13973: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13974:
13975: =item *
13976:
1.243 albertel 13977: hashref2str($hashref) : convert a hashref into a string complete with
13978: escaping and '=' and '&' separators, supports elements that are
13979: arrayrefs and hashrefs
1.191 harris41 13980:
13981: =item *
13982:
1.243 albertel 13983: arrayref2str($arrayref) : convert an arrayref into a string complete
13984: with escaping and '&' separators, supports elements that are arrayrefs
13985: and hashrefs
1.191 harris41 13986:
13987: =item *
13988:
1.243 albertel 13989: str2hash($string) : convert string to hash using unescaping and
13990: splitting on '=' and '&', supports elements that are arrayrefs and
13991: hashrefs
1.191 harris41 13992:
13993: =item *
13994:
1.243 albertel 13995: str2array($string) : convert string to hash using unescaping and
13996: splitting on '&', supports elements that are arrayrefs and hashrefs
13997:
13998: =back
13999:
14000: =head2 Logging Routines
14001:
14002:
14003: These routines allow one to make log messages in the lonnet.log and
14004: lonnet.perm logfiles.
1.191 harris41 14005:
1.1119 foxr 14006: =over 4
14007:
1.191 harris41 14008: =item *
14009:
1.243 albertel 14010: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14011:
14012: =item *
14013:
1.243 albertel 14014: logthis() : append message to the normal lonnet.log file, it gets
14015: preiodically rolled over and deleted.
1.191 harris41 14016:
14017: =item *
14018:
1.243 albertel 14019: logperm() : append a permanent message to lonnet.perm.log, this log
14020: file never gets deleted by any automated portion of the system, only
14021: messages of critical importance should go in here.
14022:
1.1119 foxr 14023:
1.243 albertel 14024: =back
14025:
14026: =head2 General File Helper Routines
14027:
14028: =over 4
1.191 harris41 14029:
14030: =item *
14031:
1.481 raeburn 14032: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14033: (a) files in /uploaded
14034: (i) If a local copy of the file exists -
14035: compares modification date of local copy with last-modified date for
14036: definitive version stored on home server for course. If local copy is
14037: stale, requests a new version from the home server and stores it.
14038: If the original has been removed from the home server, then local copy
14039: is unlinked.
14040: (ii) If local copy does not exist -
14041: requests the file from the home server and stores it.
14042:
14043: If $caller is 'uploadrep':
14044: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14045: for request for files originally uploaded via DOCS.
14046: - returns 'ok' if fresh local copy now available, -1 otherwise.
14047:
14048: Otherwise:
14049: This indicates a call from the content generation phase of the request.
14050: - returns the entire contents of the file or -1.
14051:
14052: (b) files in /res
14053: - returns the entire contents of a file or -1;
14054: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14055:
1.712 albertel 14056:
14057: =item *
14058:
14059: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14060: reference
14061:
14062: returns either a stat() list of data about the file or an empty list
14063: if the file doesn't exist or couldn't find out about it (connection
14064: problems or user unknown)
14065:
1.191 harris41 14066: =item *
14067:
1.243 albertel 14068: filelocation($dir,$file) : returns file system location of a file
14069: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14070: directory that relative $file lookups are to looked in ($dir of /a/dir
14071: and a file of ../bob will become /a/bob)
1.191 harris41 14072:
14073: =item *
14074:
14075: hreflocation($dir,$file) : returns file system location or a URL; same as
14076: filelocation except for hrefs
14077:
14078: =item *
14079:
1.1172.2.49 raeburn 14080: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14081: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14082:
1.243 albertel 14083: =back
14084:
1.608 albertel 14085: =head2 Usererfile file routines (/uploaded*)
14086:
14087: =over 4
14088:
14089: =item *
14090:
14091: userfileupload(): main rotine for putting a file in a user or course's
14092: filespace, arguments are,
14093:
1.620 albertel 14094: formname - required - this is the name of the element in $env where the
1.608 albertel 14095: filename, and the contents of the file to create/modifed exist
1.620 albertel 14096: the filename is in $env{'form.'.$formname.'.filename'} and the
14097: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14098: context - if coursedoc, store the file in the course of the active role
14099: of the current user;
14100: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14101: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14102: subdir - required - subdirectory to put the file in under ../userfiles/
14103: if undefined, it will be placed in "unknown"
14104:
14105: (This routine calls clean_filename() to remove any dangerous
14106: characters from the filename, and then calls finuserfileupload() to
14107: complete the transaction)
14108:
14109: returns either the url of the uploaded file (/uploaded/....) if successful
14110: and /adm/notfound.html if unsuccessful
14111:
14112: =item *
14113:
14114: clean_filename(): routine for cleaing a filename up for storage in
14115: userfile space, argument is:
14116:
14117: filename - proposed filename
14118:
14119: returns: the new clean filename
14120:
14121: =item *
14122:
1.1090 raeburn 14123: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14124: userspace, probably shouldn't be called directly
14125:
14126: docuname: username or courseid of destination for the file
14127: docudom: domain of user/course of destination for the file
14128: formname: same as for userfileupload()
1.1090 raeburn 14129: fname: filename (including subdirectories) for the file
14130: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14131: allfiles: reference to hash used to store objects found by parser
14132: codebase: reference to hash used for codebases of java objects found by parser
14133: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14134: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14135: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14136: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14137: context: if 'overwrite', will move the uploaded file from its temporary location to
14138: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14139: mimetype: reference to scalar to accommodate mime type determined
14140: from File::MMagic if $parser = parse.
1.608 albertel 14141:
14142: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14143: and /adm/notfound.html if unsuccessful (or an error message if context
14144: was 'overwrite').
14145:
1.608 albertel 14146:
14147: =item *
14148:
14149: renameuserfile(): renames an existing userfile to a new name
14150:
14151: Args:
14152: docuname: username or courseid of destination for the file
14153: docudom: domain of user/course of destination for the file
14154: old: current file name (including any subdirs under userfiles)
14155: new: desired file name (including any subdirs under userfiles)
14156:
14157: =item *
14158:
14159: mkdiruserfile(): creates a directory is a userfiles dir
14160:
14161: Args:
14162: docuname: username or courseid of destination for the file
14163: docudom: domain of user/course of destination for the file
14164: dir: dir to create (including any subdirs under userfiles)
14165:
14166: =item *
14167:
14168: removeuserfile(): removes a file that exists in userfiles
14169:
14170: Args:
14171: docuname: username or courseid of destination for the file
14172: docudom: domain of user/course of destination for the file
14173: fname: filname to delete (including any subdirs under userfiles)
14174:
14175: =item *
14176:
14177: removeuploadedurl(): convience function for removeuserfile()
14178:
14179: Args:
14180: url: a full /uploaded/... url to delete
14181:
1.747 albertel 14182: =item *
14183:
14184: get_portfile_permissions():
14185: Args:
14186: domain: domain of user or course contain the portfolio files
14187: user: name of user or num of course contain the portfolio files
14188: Returns:
14189: hashref of a dump of the proper file_permissions.db
14190:
14191:
14192: =item *
14193:
14194: get_access_controls():
14195:
14196: Args:
14197: current_permissions: the hash ref returned from get_portfile_permissions()
14198: group: (optional) the group you want the files associated with
14199: file: (optional) the file you want access info on
14200:
14201: Returns:
1.749 raeburn 14202: a hash (keys are file names) of hashes containing
14203: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14204: values are XML containing access control settings (see below)
1.747 albertel 14205:
14206: Internal notes:
14207:
1.749 raeburn 14208: access controls are stored in file_permissions.db as key=value pairs.
14209: key -> path to file/file_name\0uniqueID:scope_end_start
14210: where scope -> public,guest,course,group,domains or users.
14211: end -> UNIX time for end of access (0 -> no end date)
14212: start -> UNIX time for start of access
14213:
14214: value -> XML description of access control
14215: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14216: <start></start>
14217: <end></end>
14218:
14219: <password></password> for scope type = guest
14220:
14221: <domain></domain> for scope type = course or group
14222: <number></number>
14223: <roles id="">
14224: <role></role>
14225: <access></access>
14226: <section></section>
14227: <group></group>
14228: </roles>
14229:
14230: <dom></dom> for scope type = domains
14231:
14232: <users> for scope type = users
14233: <user>
14234: <uname></uname>
14235: <udom></udom>
14236: </user>
14237: </users>
14238: </scope>
14239:
14240: Access data is also aggregated for each file in an additional key=value pair:
14241: key -> path to file/file_name\0accesscontrol
14242: value -> reference to hash
14243: hash contains key = value pairs
14244: where key = uniqueID:scope_end_start
14245: value = UNIX time record was last updated
14246:
14247: Used to improve speed of look-ups of access controls for each file.
14248:
14249: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14250:
1.1172.2.13 raeburn 14251: =item *
14252:
1.749 raeburn 14253: modify_access_controls():
14254:
14255: Modifies access controls for a portfolio file
14256: Args
14257: 1. file name
14258: 2. reference to hash of required changes,
14259: 3. domain
14260: 4. username
14261: where domain,username are the domain of the portfolio owner
14262: (either a user or a course)
14263:
14264: Returns:
14265: 1. result of additions or updates ('ok' or 'error', with error message).
14266: 2. result of deletions ('ok' or 'error', with error message).
14267: 3. reference to hash of any new or updated access controls.
14268: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14269: key = integer (inbound ID)
1.1172.2.13 raeburn 14270: value = uniqueID
14271:
14272: =item *
14273:
14274: get_timebased_id():
14275:
14276: Attempts to get a unique timestamp-based suffix for use with items added to a
14277: course via the Course Editor (e.g., folders, composite pages,
14278: group bulletin boards).
14279:
14280: Args: (first three required; six others optional)
14281:
14282: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14283: docssequence, or name of group
14284:
14285: 2. keyid (alphanumeric): name of temporary locking key in hash,
14286: e.g., num, boardids
14287:
14288: 3. namespace: name of gdbm file used to store suffixes already assigned;
14289: file will be named nohist_namespace.db
14290:
14291: 4. cdom: domain of course; default is current course domain from %env
14292:
14293: 5. cnum: course number; default is current course number from %env
14294:
14295: 6. idtype: set to concat if an additional digit is to be appended to the
14296: unix timestamp to form the suffix, if the plain timestamp is already
14297: in use. Default is to not do this, but simply increment the unix
14298: timestamp by 1 until a unique key is obtained.
14299:
14300: 7. who: holder of locking key; defaults to user:domain for user.
14301:
14302: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14303: retrying); default is 3.
14304:
14305: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14306:
14307: Returns:
14308:
14309: 1. suffix obtained (numeric)
14310:
14311: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14312:
14313: 3. error: contains (localized) error message if an error occurred.
14314:
1.747 albertel 14315:
1.608 albertel 14316: =back
14317:
1.243 albertel 14318: =head2 HTTP Helper Routines
14319:
14320: =over 4
14321:
1.191 harris41 14322: =item *
14323:
14324: escape() : unpack non-word characters into CGI-compatible hex codes
14325:
14326: =item *
14327:
14328: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14329:
1.243 albertel 14330: =back
14331:
14332: =head1 PRIVATE SUBROUTINES
14333:
14334: =head2 Underlying communication routines (Shouldn't call)
14335:
14336: =over 4
14337:
14338: =item *
14339:
14340: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14341:
14342: =item *
14343:
14344: reply() : uses subreply to send a message to remote machine, logs all failures
14345:
14346: =item *
14347:
14348: critical() : passes a critical message to another server; if cannot
14349: get through then place message in connection buffer directory and
14350: returns con_delayed, if incapable of saving message, returns
14351: con_failed
14352:
14353: =item *
14354:
14355: reconlonc() : tries to reconnect lonc client processes.
14356:
14357: =back
14358:
14359: =head2 Resource Access Logging
14360:
14361: =over 4
14362:
14363: =item *
14364:
14365: flushcourselogs() : flush (save) buffer logs and access logs
14366:
14367: =item *
14368:
14369: courselog($what) : save message for course in hash
14370:
14371: =item *
14372:
14373: courseacclog($what) : save message for course using &courselog(). Perform
14374: special processing for specific resource types (problems, exams, quizzes, etc).
14375:
1.191 harris41 14376: =item *
14377:
14378: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14379: as a PerlChildExitHandler
1.243 albertel 14380:
14381: =back
14382:
14383: =head2 Other
14384:
14385: =over 4
14386:
14387: =item *
14388:
14389: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 14390:
14391: =back
14392:
14393: =cut
1.877 foxr 14394:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>